Kyle
Kyle

Reputation: 1173

Using has_many through associations in Rails 4

I'm trying to create a few simple relations in my Rails 4 application. I have three models: user, list, word.

This is for a simple 'list' application, where each user has_many words through lists.

I currently have the following associations...

User model:

class User < ActiveRecord::Base
    has_many :words through :lists
end

List model:

class List < ActiveRecord::Base
    has_many :words
    belongs_to :user
end

Word model:

class Word < ActiveRecord::Base
    belongs_to :list
end

I'm not sure how to create the relationships through the console. For example...

>   user = User.create(name: "Kyle")
>   list = List.create(name: "List One")
>   word = Word.create(word: "StackOverflow")
>
>   list.push(word)     # add word to list
>   user.push(list)     # add list to user

Can someone please give an example on how to correctly create these associations.

Upvotes: 0

Views: 864

Answers (1)

Prakash Murthy
Prakash Murthy

Reputation: 13077

User model

class User < ActiveRecord::Base
  has_many :lists
  has_many :words, through: :lists
end

List model

class List < ActiveRecord::Base
  has_many :words
  belongs_to :user
end

Word model

class Word < ActiveRecord::Base
  belongs_to :list
end

creating objects:

> user = User.create(name: "Kyle")
> list = List.create(name: "List One")
> word = Word.create(word: "StackOverflow")

# Add word to a list
> list.words << word
> list.words.create(word: "LinkedIn") # Add a newly created word directly
> list.words << Word.find(params[:word_id]) # Add an existing word after finding it by its id

# Associate a list to a user
> user.lists << list

Upvotes: 1

Related Questions