【问题标题】:Rails - Don't know how to save data from a form into another modelRails - 不知道如何将表单中的数据保存到另一个模型中
【发布时间】:2015-06-10 18:58:13
【问题描述】:

我有一个 Movie 模型和一个 Actor 模型:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-16
      • 2023-04-08
      • 2021-05-07
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多