我要提交的表单如下(从“显示方法”视图中):
<%= form_for(Photo.new, :remote => true, html: {multipart: :true}) do |f| %>
<%= f.label :title, 'Title' %>
<%= f.text_field :title %>
<%= f.label :image, 'Choose Image' %>
<%= f.file_field :image %>
<%= f.hidden_field :item_id, :value => @item.id %>
<%= f.submit 'Add' %>
<% end %>我试图使用以下创建方法:
def show
@item = Item.find(params[:id])
end
def create
@item = Item.find(params[:item_id])
@photo = Photo.new(photo_params)
redirect_to edit_photos_url, notice: 'Photo uploaded' if @photo.save
end这就是日志生成的内容:
Started POST "/photos" for ::1 at 2015-07-03 21:17:10 -0400
Processing by PhotosController#create as HTML
Parameters: {"utf8"=>"✓", "photo"=>{"title"=>"sdb", "image"=># <ActionDispatch::Http::UploadedFile:0x007fe301a2ebf8 @tempfile=#<Tempfile:/var/folders/d8/hx2wgfwx7m77c6mjwx2pffcc0000gq/T/RackMultipart20150703-35083-rt86ai.png>, @original_filename="Screen Shot 2015-06-28 at 9.23.31 PM.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"Screen Shot 2015-06-28 at 9.23.31 PM.png\"\r\nContent-Type: image/png\r\n">, "item_id"=>"27"}, "commit"=>"Add"}
Can't verify CSRF token authenticity
Completed 404 Not Found in 1ms
ActiveRecord::RecordNotFound (Couldn't find Item without an ID):
app/controllers/photos_controller.rb:13:in `create'item_id似乎是提交的,但却不起作用?
我也尝试过实现会话,这会更理想。我在items控制器的create方法中完成了以下操作:
remember_item @item 调用助手中的方法:
def remember_item(item)
cookies.permanent.signed[:item_id] = item.id
session[:item_id] = item.id
end我检查了会话变量,并且:item_id在会话中被正确地传递了。我试过以下几种方法:
def create
@item = Item.find(session[:item_id])
@photo = @item.photos.build(photo_params)
redirect_to edit_photos_url, notice: 'Photo uploaded' if @photo.save
end这也不起作用,产生了以下错误:
Couldn't find Item without an ID我真的很想让后者去工作。有什么建议吗?
发布于 2015-07-04 04:03:28
照片中包含了item_id。
@item = Item.find params[:photo][:item_id]应该给你你想要的。
发布于 2015-07-04 04:05:31
如果你仔细观察,你提交的实际上是
params
=> {photo: {item_id: 1, **other_attrs}}
params[:item_id]
=> nil
params[:photo][:item_id]
=> 1这是因为item_id作为助手在您的表单中,而表单助手认为它是photo的属性。
https://stackoverflow.com/questions/31216727
复制相似问题