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

时间:2015-07-04 03:57:45

标签: ruby-on-rails session params

我有以下表单我试图提交(从show方法视图):

  <%= 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

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

2 个答案:

答案 0 :(得分:0)

item_id包含在照片参数

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

应该给你你想要的东西。

答案 1 :(得分:0)

如果你仔细观察,你提交的内容实际上是

item_id

这是因为photo在您的表单中作为帮助,而表单助手认为它是{{1}}的属性。