Rails - 不知道如何将表单中的数据保存到另一个模型中

时间:2015-06-10 18:58:14

标签: ruby-on-rails ruby

我有一个电影模型和一个演员模型:

class Movie < ActiveRecord::Base

belongs_to :genre
has_many :reviews 
has_many :actors

end



class Actor < ActiveRecord::Base

belongs_to :movies

end

这些是每个模型的属性:

create_table "actors", force: :cascade do |t|
t.string   "name"
t.text     "bio"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer  "movie_id"
end

create_table "movies", force: :cascade do |t|
t.string   "title"
t.integer  "duration"
t.date     "release_date"
t.text     "plot"
t.string   "director"
t.text     "cast"
t.datetime "created_at",   null: false
t.datetime "updated_at",   null: false
end

当用户填写表单以创建新电影时,我希望来自“演员”字段的输入保存到Actor模型。我需要在控制器中执行哪些操作以及在表单中需要执行哪些操作?

我看了看并尝试了以下内容,但我仍然陷入困境:

Rails Updating Data in one Model from another Model's Controller

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

How can I update and save one model from another in Rails?

http://railscasts.com/episodes/196-nested-model-form-part-1

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:3)

您想要创建嵌套表单。您需要将accepts_nested_attributes_for :actors添加到电影模型中,然后在表单中构建一个子表单...这里有更好的解释:

http://www.theodinproject.com/ruby-on-rails/advanced-forms

向下滚动到“嵌套表格”。