Rails, 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

Answers


so network has_may users and 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

in the user model:

class User < ActiveRecord::Base
belongs_to :network

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.


Need Your Help

Do I have access to the TCP/IP packet's details from the CGI level?

cgi request webserver tcp-ip

CGI scripts, for example web applications, operate on the CGI interface of the webserver.

WP 8 - How to Open Menu with Application Bar Icon Button

c# xaml windows-phone-8

My question is clear and short i think. How can i open application bar with applicationbar icon button ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.