Railsのform_forでの注意

[rails]
# view
<% form_for :hoge, :url => {:action => :update} do |f| %>
<% f.hidden_field :id, {:value => @hoge.id} %>
<% f.text_field :name, {:value => @hoge.name} %>
<% f.submit %>
<% end %>
[/rails]
[rails]
# controller
def update
if params[:hoge]
hoge = Hoge.find_by_id(params[:hoge][:id])
hoge.attributes = params[:hoge]
hoge.save!
end
end
[/rails]
のような書き方をするとうまく保存されません
WARNING: Can’t mass-assign these protected attributes: id
のような警告をlogに吐きます
どうやらidは上書きも認められてないようです
hidden_fieldではなく、form_forの引数として渡すとうまく行きます

[rails]
# view
<% form_for :hoge, :url => {:action => :update, :id => @hoge.id} do |f| %>
<% # f.hidden_field :id, {:value => @hoge.id} %>
<% f.text_field :name, {:value => @hoge.name} %>
<% f.submit %>
<% end %>
[/rails]
[rails]
# controller
def update
if params[:hoge]
# hoge = Hoge.find_by_id(params[:hoge][:id])
hoge = Hoge.find_by_id(params[:id])
hoge.attributes = params[:hoge]
hoge.save!
end
end
[/rails]

これでうまいこと更新出来ます

カテゴリー: All   タグ: ,   この投稿のパーマリンク

コメントをどうぞ

メールアドレスが公開されることはありません。

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>