I am uploading an image and want to associate it with the current project I’m in. I’m inside a project at the URL example.com/projects/1 and render this form:
<%= semantic_form_for @image, :html => { :multipart => true } do |f|%>
<%= f.semantic_errors %>
<%= f.inputs do %>
<%= f.input :title %>
<%= f.input :description %>
<%= f.input :image, :as => :file %>
<% end %>
<%= f.buttons do %>
<%= f.commit_button :label => 'Upload Image', :button_html => { :class => "btn primary" } %>
<% end %>
<% end %>
I’ve set in image.rb model, belongs_to :project and in project.rb model, has_many :images
My images_controller.rb create method looks like this:
def create
image = params[:image]
if user_signed_in?
@image = Image.new(:title => image[:title],
:description => image[:description],
:user_id => current_user.id,
:project_id => params[:id])
if @image.save
flash[:success] = "Successfully uploaded an image"
redirect_to project_path(params[:id]) and return
else
flash[:error] = "Error with image upload"
redirect_to new_image_path and return
end
else
redirect_to root_path
end
end
The image is created but fails to associate the image with the project_id. I know the problem is with params[:id] not pulling in the project_id, how do I pull the project id from the URL and associate it with the image?
You should use your associations to create the new Image.
if that does not work, please post the contents of your routes.rb and the url that is hit from the post request.