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 <开发者_Go百科=> 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
@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])
精彩评论