Rails 创建方法:隐藏字段标签提交但不工作 & 会话参数不工作

Rails create method: hidden field tag submitting but not working & sessions param not working

我尝试提交以下表格(从显示方法视图):

  <%= 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好像提交了,但是还是不行?

我也尝试过实现会话,这会更理想。我在项目控制器的 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

我真的很想让后者工作。建议?

item_id 包含在照片参数中

@item = Item.find params[:photo][:item_id]

应该给你你想要的。

仔细一看,你提交的其实是

params
=> {photo: {item_id: 1, **other_attrs}}
params[:item_id]
=> nil
params[:photo][:item_id]
=> 1

那是因为 item_id 在您的表单中作为助手,而表单助手认为它是 photo 的 属性。