Rails: how to convert has_one to has_many association

Assuming

class Kid < ActiveRecord::Base
    has_one :friend
end

class Friend< ActiveRecord::Base
  belongs_to :kid
end

      

How can I change this to

class Kid < ActiveRecord::Base
    has_many :friends
end

class Friend< ActiveRecord::Base
  belongs_to :kid
end

      

Appreciate your understanding ...

+3


source to share


2 answers


Collection

The bottom line is that if you change your link to a relationship has_many :x

, it will create a collection of associative data; not one object, as with a single association

The difference here does not affect its implementation, but it does matter a lot to how you use the association in your application. I will explain how


Fix

First, you are correct that you can simply change has_one :friend

to has_many :friends

. You have to be careful to understand why this works:

enter image description here

ActiveRecord associations work by associating something called foreign_keys

in your data. These are column references to the "primary key" (ID) of your parent class, allowing Rails / ActiveRecord to bind them



As long as you maintain foreign_key

for all your facilities Friend

, you will not get system problems.

-

Data

To expand on this idea, you should remember that when creating an association, has_many

Rails / ActiveRecord will pull in a lot of records every time you reference the association.

This means that if you call @kind.friends

, you will no longer receive one object back. You will get all the objects from the datatable - this means that you will need to call the loop .each

to manipulate / display them:

@kid = Kid.find 1
@kid.friends.each do |friend|
   friend.name
end

      

If, after making these changes, you have a problem calling a method save

on order.save

that tells you it already exists and that doesn't allow you to actually have many records order

for one customer

, you may need to call orders.save (: validate => false)

+6


source


You answered the question. Just change it in the model as you showed.



+3


source







All Articles