如何使用accepts_nested_attributes_for在Rails3中创建嵌套对象?
我不知道如何设置一个表单来创建新的 Study
,同时创建相关的 StudySubject
和 Facility
。 user_id
、facility_id
和 study_subject_id
必须可用才能创建 Study
对象,如您在数据库中看到的那样关系模型。
这是研究
的迁移。其他表不包含外键。
def self.up
create_table :studies do |t|
t.references :user
t.references :facility
t.references :subject
t.date "from"
t.date "till"
t.timestamps
end
add_index :studies, ["user_id", "facility_id", "subject_id"], :unique => true
end
这些模型定义了以下关联。
# user.rb
has_many :studies
# subject.rb
has_many :studies
# facility.rb
has_many :studies
# study
belongs_to :user
belongs_to :subject
belongs_to :facility
问题
1) has_many
和 belongs_to
定义正确吗?
2) 如何使用 accepts_nested_attributes_for研究一个>?
3) 一项研究只能属于一个用户。我是否需要将 user_id
添加到每个其他对象中来存储关联?
经过两周的广泛学习,我对 Rails 完全陌生。抱歉,可能问了一个愚蠢的问题。
I cannot figure out how I can setup a form that will create a new Study
while also creating the related StudySubject
and the Facility
. The user_id
, facility_id
and study_subject_id
have to be available to create the Study
object as you can see in the database relation model.
Here is the migration for the studies
. The other tables do not contain foreign keys.
def self.up
create_table :studies do |t|
t.references :user
t.references :facility
t.references :subject
t.date "from"
t.date "till"
t.timestamps
end
add_index :studies, ["user_id", "facility_id", "subject_id"], :unique => true
end
The models define the following associations.
# user.rb
has_many :studies
# subject.rb
has_many :studies
# facility.rb
has_many :studies
# study
belongs_to :user
belongs_to :subject
belongs_to :facility
Questions
1) Are the has_many
and belongs_to
definitions correct?
2) How can I create a study
using accepts_nested_attributes_for?
3) A study should only belong to one user. Do I need to add the user_id
into every other object to store the association?
I am totally new to Rails since 2 weeks of extensive learning. Sorry for a stupid question maybe.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。有用。一位好朋友提供了帮助。这就是我们设置的。
请注意,我同时将
StudySubject
重命名为Subject
。模型
study.rb code>
控制器
studies_controller.rb
我使用devise 用于身份验证,cancan 用于授权。这就是
current_user
在控制器中可用的原因。新的研究视图
new.html.erb
我希望这能为您节省一些时间。我花了很多时间来了解如何设置。
Yeah. It works. A good friend offered his help. This is what we set up.
Please mind that I renamed
StudySubject
toSubject
in the meantime.The model
study.rb
The controller
studies_controller.rb
I use devise for authentication and cancan for authorization. That is why
current_user
is available in the controller.The new study view
new.html.erb
I hope this will save you some time. I spent a lot of time to realize how things have to be set up.