我正在上传一张图片,想要将它与我当前的项目相关联。我在URL example.com/projects/1的一个项目中并呈现此表单:
<%= 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 %>
我已经设置了image.rb模型,belongs_to :project
和project.rb模型,has_many :images
我的images_controller.rb创建方法如下所示:
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
已创建图像,但无法将图像与project_id相关联。我知道问题是params[:id]
没有拉入project_id,如何从URL中提取项目ID并将其与图像相关联?
答案 0 :(得分:1)
您应该使用关联来创建新图像。
@image = Project.find(params[:id]).images.create(:title => image[:title],
:description => image[:description],
:user => current_user)
if @image.save...
如果这不起作用,请发布routes.rb的内容和从帖子请求中点击的网址。