Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a one to many relationship?

I have the following models:

User (id, name, network_id) Network(id, title) 

What kind of Rails model assoc do I need to add so that I can do:

@user.network.title @network.users 

Thanks

like image 684
AnApprentice Avatar asked Dec 18 '11 21:12

AnApprentice


People also ask

What is a one-to-many relationship example?

Some common examples of one-to-many relationships are: A car maker makes many different models, but a particular car model is built only by a single car maker. One customer may make several purchases, but each purchase is made by a single customer.

How do you create a one-to-many relationship in SQL?

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa. To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

How do you write a one-to-many relationship query?

How to implement one-to-many relationships when designing a database: Create two tables (table 1 and table 2) with their own primary keys. Add a foreign key on a column in table 1 based on the primary key of table 2. This will mean that table 1 can have one or more records related to a single record in table 2.

How do I create a one-to-many relationship in Excel?

In the Manage Relationships box, click New. In the Create Relationship box, click the arrow for Table, and select a table from the list. In a one-to-many relationship, this table should be on the many side.


2 Answers

so network has_many users and a user belongs_to network.

Just add a network_id to users table if you still haven't and also since it's a foreign_key is worth indexing it.

rails generate migration AddNetworkIdToUsers

class AddNetworkIdToUsers < ActiveRecord::Migration   def change     add_column :users, :network_id, :integer     add_index  :users, :network_id   end end 

In the network model do:

class Network < ActiveRecord::Base   has_many :users end 

In the user model do:

class User < ActiveRecord::Base   belongs_to :network end 
like image 54
daniel Avatar answered Sep 23 '22 05:09

daniel


According to your database-setup, you just have to add the following lines to your models:

class User < ActiveRecord::Base   belongs_to :network   # Rest of your code here end  class Network < ActiveRecord::Base   has_many :users   # Rest of your code here end 

In case you have a setup without network_id, you should go with daniels answer.

like image 39
klaffenboeck Avatar answered Sep 22 '22 05:09

klaffenboeck