LoginSignup
0

More than 1 year has passed since last update.

Formオブジェクトのedit定義

Posted at

例えばitemsテーブルとtagsテーブルの2つを合わせたFormオブジェクトがあったとしたら、それを編集するためのeditアクションは下記のようになる。

items_controller.rb
def edit
    @item = Item.find(params[:id])
    @tag = @item.tag
    item_attributes = @item.attributes
    tag_attributes = @tag.attributes
    item_tag = item_attributes.merge(tag_attributes)
    @item_tag = item_tag.new(item_tag)
end

attributesメソッドでそれぞれの値をハッシュとして取り出し、それらをmergeメソッドでハッシュを結合することで、編集したいitem_tagの情報を取り出すことができる。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0