Shalafister
Shalafister

Reputation: 399

Carrierwave - upload photo from index page

I have two associated models, Boats has_many :pictures , Picture Model belongs_to :boat and these are nested routes;

resources :boats, except: :destroy do
      resources :pictures
end

So, I have index page, where all the boats are showing there. But I wanted to add upload photo form there too, after I will add a JQuery option. Put I have a problem with the form. As I am in the indexpage, I have to send the the form to #create action from the index page;

Here is the pictures controller;

class PicturesController < ApplicationController
  before_action :logged_in_user
  before_filter :load_parent

  def index
    @pictures = @boat.pictures.all 
  end

  def new
    @picture = @boat.pictures.new
  end

  def show
    @picture = @boat.pictures.find(params[:id])
  end


  def create

    @picture = @boat.pictures.new(picture_params)
    if @picture.save
      #flash[:success] = "Continue from here"

      redirect_to boat_pictures_path(@boat)
      #redirect_to boat_path(@boat)
    else
      render 'new' 
    end
  end

  def edit
    @picture = Picture.find(params[:id])
  end

  def update
    @picture = @boat.pictures.find(params[:id])

    if @picture.update_attributes(picture_params)
      flash[:notice] = "Successfully updated picture."
      render 'index'
    else
      render 'edit'
    end
  end

  def destroy

    @picture = @boat.pictures.find(params[:id])
    @picture.destroy

    flash[:notice] = "Successfully destroyed picture."
    redirect_to boat_pictures_path(@boat)
    #redirect_to boat_path(@boat)
  end


  private

    def picture_params
      params.require(:picture).permit(:name, :image)
    end

    def load_parent
     @boat = Boat.find(params[:boat_id])
    end

end

Here is the index view;

<% @pictures.each do |pic| %>
</br>
<%= pic.name %>
<%= image_tag pic.image_url(:thumb).to_s  %>
<%= link_to "edit", edit_boat_picture_path(@boat, pic) %> |
<%= link_to 'Destroy', boat_picture_path(@boat, pic), confirm: 'Are you sure?', method: :delete %> | 
</br>
<% end %>
<%= link_to "add", new_boat_picture_path(@boat, @picture) %>

<%= form_for Picture.new, :as => :post, :url => new_boat_picture_path(@boat, @picture) do |f| %>
 <%= f.file_field :image, multiple: true, name: "picture[image]" %>   

<% end %>

I think <%= form_for Picture.new, :as => :post, :url => new_boat_picture_path(@boat, @picture) do |f| %> is the problem the url is not correct. There is no submit button to send it but it is because I will use JQuery file upload.

Upvotes: 0

Views: 25

Answers (1)

crispychicken
crispychicken

Reputation: 2662

Yes, the part is wrong for sure.

In your console type in: rake routes and look for the correct path in the list.

I think it will be boat_pictures_path(@boat)

Upvotes: 1

Related Questions