简体   繁体   中英

rails belongs_to has_one. need some explanation

I've got two models:

Customer and Contact

Customers table has columns :id, :firstName, :lastName

Contacts table has columns :id, :cid, :hphone, :cphone

So if Customers table has data

1  Josh   McDonnel

Then Contacts table has corresponding

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

What associations can I use here?

Will Contact have

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

What should the Customer class have?

Also, how will a simple find_byXXX look like if I want to get all customers ( firstName , lastName and corresponding hphone and cphone )

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

You are close, but your belongs_to should be this. :foreign_key should be the name of the field storing a reference to the primary id:

belongs_to :customer, :foreign_key => "cid"

And in your Customer.rb class:

has_one :contact, :foreign_key => "cid"

Finally, your search might look like this:

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

Then you could use it in a loop in your view:

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

Incidentally , if you had used customer_id instead of cid your association could just be:

#Contact.rb
belongs_to :customer

#Customer.rb
has_one :contact

The object who's table contains the foreign key "belongs_to" the object which doesn't.

If Customer has_one Contact and Contact belongs_to Customer then the foreign key ("customer_id" by default) will exist in the contacts table.

You probably don't want to use "id" as the foreign key because "id" is reserved for the column containing the id of the contact. Specifying a classname is not required either, because the name of the class is the same as the name of the relation (in this case, "customer").

Customer would have:

has_one :contact

Contact would have:

belongs_to :customer

Then if you wanted to find a certain customer's contact you could just call:

@customer.contact

or vice versa.

Your other question regarding find_by_XXX is a little vague. If you want to find all Customers with the first name "John" you could use:

@customers_named_john = Customer.find_by_firstName("John")

But I'm not sure this is what you're asking about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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