2011-02-26 77 views
0

基本上我有两个模型:用户和教父。教父表具有三列:如何管理具有两个外键的模型的形式

  • USER_ID(FK - >用户)
  • user_godfather_id(FK - >用户)
  • 描述(文本)

内的每个模型类,我添加了以下关联:

class User < ActiveRecord::Base 

    has_many :godfathers # for user_id 
    has_many :other_godfathers, :foreign_key => "user_godfather_id", :class_name => "Godfather" 

    accepts_nested_attributes_for :godfathers 
end 

class Godfather < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :user_godfather, :class_name => "User" 
end 

现在我的问题是关于如何管理此嵌套属性的编辑窗体关系。 这里是我的形式看起来像此刻(使用nested_form_for宝石):

<%= nested_form_for @user do |f| %> 
      <%= f.fields_for :godfathers do |godfather_form| %> 
       # Here I have an ID text field but what I want instead is 
       # to provide a username for this godfather. 
       <%= godfather_form.label :user_godfather_id %> 
       <%= godfather_form.text_field :user_godfather_id %> 

       <%= godfather_form.label :description %> 
       <%= godfather_form.text_field :description %> 

       <%= godfather_form.link_to_remove "Remove this godfather" %> 
      <% end %> 
      <%= f.link_to_add "Add a godfather", :godfathers %> <br/><br/> 
<%= f.submit "Update Godfathers" %> 

因此,正如我在评论中说,我的目标是能够提供教父用户名,而不是一个ID的。顺便说一下,该用户名是User表中的一列。

有关我应该怎么做的任何想法?

谢谢!

回答

1

只需使用不同的名称为关系

class User < ActiveRecord::Base 

    has_many :godfathers # for user_id 
    has_many :some_other_godfathers, :foreign_key => "user_godfather_id", :class_name => "Godfather" 

    accepts_nested_attributes_for :godfathers 
end 

现在你可以使用教父和some_other_godfathers。

希望对您有所帮助:-)

+0

谢谢!事实上,我没有注意到这一点!但我的问题更多的是关于表单本身!如何编写我的nested_form_for,例如我可以提供教父(这是用户表中的一列)的用户名而不是它的ID!任何想法? +1帮助无论如何:) – 2011-02-27 12:01:01

+0

我想只是将其更改为:user_godfather_name并只在您的控制器中搜索该名称... – Hock 2011-02-28 01:58:39

相关问题