0
我正在上传图像,并希望将其与当前项目相关联。我位于URL example.com/projects/1的项目中并呈现此内容形式:Rails 3.1:将project_id与新上传的图像相关联
<%= 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,我该如何从网址中提取项目ID并将其与图片关联?
感谢您的帮助。这不起作用,我得到了错误“找不到没有ID的项目”。 POST网址:开始POST“/ images”。在routes.rb我有两个资源:图像和资源:项目 – ramz15 2012-02-06 22:25:02
这就是为什么你得到这个错误,URL是错误的,不包含ID参数。您需要传递它,隐藏字段是一种相对简单的方法,另一种方法是使用嵌套资源。 http://guides.rubyonrails.org/routing.html#nested-resources – Gazler 2012-02-06 22:28:29
谢谢Gazler!我用隐藏字段解决了这个问题,对于n00b问题感到抱歉:) – ramz15 2012-02-06 23:32:50