Satchel
Satchel

Reputation: 16724

has_many _through not working in Rails 3 after upgrade from Rails 2

I have the following in my controller:

@campaign = Campaign.where(:id => params[:id])
@companies = @campaign.companies.sort { |a,b| a.name <=> b.name` }

The second line gives me an unknown method for companies and it worked fine before.

This is in my campaign model:

has_many :companies, :through => :contacts, :uniq => true

I tried the following and it still didn't fix it:

has_many :companies, :through => :contacts, :uniq => true, :source => :company

Upvotes: 1

Views: 134

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

@campaign = Campaign.where(:id => params[:id])

returns an array of results (probably just one item, but still an array). The "No Method Error" you're receiving is because the Array class doesn't have a companies method.

You either want to call .first on the result set:

@campaign = Campaign.where(:id => params[:id]).first

Or just use .find:

@campaign = Campaign.find(params[:id])

Upvotes: 2

Related Questions