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
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.
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 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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With