【问题标题】:rails belongs_to has_one. need some explanationrails belongs_to has_one。需要一些解释
【发布时间】:2010-01-22 21:43:49
【问题描述】:

我有两个模型:

CustomerContact

Customers 表有列:id, :firstName, :lastName

Contacts 表有列:id, :cid, :hphone, :cphone

所以如果客户表有数据

1  Josh   McDonnel

那么Contacts表就有对应的

5   1   947-245-2342 342-543-8585 

我可以在这里使用哪些关联?

联系人有

belongs_to :customer, :foreign_key => "id", :class_name => "Customer"

Customer 类应该有什么?

另外,如果我想吸引所有客户(firstNamelastName 和对应的hphonecphone),那么简单的find_byXXX 会是什么样子

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    记住一条规则:包含外键的表属于_该外键引用的表。

    【讨论】:

      【解决方案2】:

      你很接近,但你的belongs_to 应该是这个。 :foreign_key 应该是存储对主 ID 的引用的字段的名称:

      belongs_to :customer, :foreign_key => "cid"
      

      在你的Customer.rb 课堂上:

      has_one :contact, :foreign_key => "cid"
      

      最后,您的搜索可能如下所示:

      @customers = Customer.all(:include => :contact)
      

      然后你可以在你的视图中循环使用它:

      <% @customers.each do |customer| %>
         <p>Name: <%= customer.firstName %> <%= customer.lastName %></p>
         <p>Home: <%= customer.contact.hphone %></p>
         <p>Work: <%= customer.contact.cphone %></p>
      <% end %>
      

      顺便说一句,如果您使用 customer_id 而不是 cid,您的关联可能只是:

      #Contact.rb
      belongs_to :customer
      
      #Customer.rb
      has_one :contact
      

      【讨论】:

      • 感谢您的精彩解释。我正在尝试进行您建议的搜索,但在我的情况下 cid 是 varchar 但 id 是整数。这样搜索不起作用并引发错误。我可以回去将 cid 更改为整数,但是说,例如我不想更改它。解决办法是什么?
      • 当然,只需运行迁移即可。 (首先备份您的数据!)运行此代码:script/generate migration ChangeContactsForeignKey 并使用此代码:pastie.org/790513
      • 当然,完成这些步骤后使用rake db:migrate
      • @doug 我在尝试获取所有拥有电话号码的客户时遇到问题。这就是我正在做的事情:pastie.org/790718
      • @Omnipresent pastie.org/790728 请记住,因为它是has_one,所以include 应该引用:contact 单数,但是SQL 条件应该引用表名,它是复数。
      【解决方案3】:

      表中的对象包含外键“belongs_to”,不包含的对象。

      如果 Customer has_one Contact 和 Contact belongs_to Customer,则外键(默认为“customer_id”)将存在于联系人表中。

      您可能不想使用“id”作为外键,因为“id”是为包含联系人 id 的列保留的。也不需要指定类名,因为类的名称与关系的名称相同(在本例中为“客户”)。

      客户会:

      has_one :contact
      

      联系方式:

      belongs_to :customer
      

      如果你想找到某个客户的联系人,你可以打电话:

      @customer.contact
      

      反之亦然。

      您关于 find_by_XXX 的其他问题有点含糊。如果您想查找名字为“John”的所有客户,您可以使用:

      @customers_named_john = Customer.find_by_firstName("John")
      

      但我不确定这是您要问的问题。

      【讨论】:

      • 在他的数据库模式中,他似乎想将Customerid 存储在cid 中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多