Rails belongs to_to has_one. need some explanation

I have two models:

Customer and Contact

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

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

So, if the Customers table has data

1  Josh   McDonnel

Then the contact table has the corresponding

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

What associations can I use here?

Will contact

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

What should the Customer class have?

Also, it looks simple find_byXXXif I want to get all the clients ( firstName, lastNameand the corresponding hphoneand cphone)

+3
source share
3 answers

You are close, but yours belongs_toshould be like that. :foreign_keyshould be the name of the field in which the link to the primary identifier is stored:

belongs_to :customer, :foreign_key => "cid"

And in your class 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
+4

: _ , .

+8

, "" , .

, ( "customer_id" ) .

, "id" , "id" , . , ( "" ).

:

has_one :contact

:

belongs_to :customer

Then, if you want to find a specific contact with the client, you can simply call:

@customer.contact

or vice versa.

Your other question regarding find_by_XXX is a bit vague. If you want to find all Clients with the name "John", you can use:

@customers_named_john = Customer.find_by_firstName("John")

But I'm not sure that this is what you are asking for.

+1
source

Source: https://habr.com/ru/post/1729633/


All Articles