简体   繁体   English

Rails has_one关联

[英]Rails has_one association

I have three models: 我有三种模式:

class User < ActiveRecord::Base
  has_many :basiccases
end

class Basiccase < ActiveRecord::Base
  belongs_to :user
  belongs_to :form3_c
end

class Form3C < ActiveRecord::Base
  has_one :basiccases
end

How can I add a new Form3C to the Basiccase ? 我如何添加一个新的Form3CBasiccase Do I need to use a Basiccase controller or Form3C controller to create a form? 我需要使用Basiccase控制器还是Form3C控制器来创建表单? If I use Form3cController how can I set the foreign key in the BasiccaseController? 如果使用Form3cController如何在BasiccaseController?设置外键BasiccaseController?

Relationships like has_one are defined on models rather than controllers. has_one这样的关系是在模型而不是控制器上定义的。 I think you want this (to be able to add a Form3c to a Basiccase --not sure which direction you want the relationship to go): 我认为您想Form3c (能够将Form3c添加到Basiccase不确定您希望关系朝哪个方向前进):

class Form3c < ActiveRecord::Base
  belongs_to :basiccase
end

class Basiccase < ActiveRecord::Base
  belongs_to :user
  has_one :form3c
end

For tips on building the controller and form (view), look at this Rails tutorial , starting around section 6. 有关构建控制器和表单(视图)的技巧,请参阅此Rails教程 ,从第6节开始。

Though your naming of model is not that convincing, I am assuming your basiccases table has one column form3c_id . 尽管您对模型的命名不那么令人信服,但我假设您的basiccases表具有一列form3c_id

You need to create a form for form3c object then in controller you can build a basiccase object like @form3c_build_basiccase which will automatically take form3c_id as a foreign key. 您需要为form3c对象创建一个表单,然后在控制器中可以构建一个基本basiccase对象,例如@form3c_build_basiccase ,它将自动将form3c_id用作外键。 Refer to this rails cast . 请参阅此rails cast

Or you may go for form3c model accepts_nested_attributes_for :basiccase . 或者您可以使用form3c模型accepts_nested_attributes_for :basiccase See about it here . 在这里查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM