简体   繁体   中英

rails metasearch undefined method 'company_id'

I'm new to rails and need your help for what should be a simple problem.

when I run this code:

@search = User.search(params[:search])
@foundusers = @search.all.paginate :page => params[:page], :per_page => 20
@user = @search.where("users.id = ?", params[:id])
if @user.nil?
  @user = @foundusers.first
end
unless @user.company_id.nil?
  @company = Company.find(@user.company_id)
end

I get following error statement: undefined method `company_id' for #

I dont understand because the query on the database is correct (SELECT users .* FROM users LEFT OUTER JOIN companies ON companies . id = users . company_id WHERE ((( users . firstname LIKE '%s%' OR users . lastname LIKE '%s%') OR companies . name LIKE '%s%')) AND (users.id = '11'))

and the company_id for this user is not empty.

When I type puts @user.name, instead of giving me the user name, it gives me 'User'

Many thanks for your help.

@user.name prints User because .where("users.id = ?", params[:id]) still return an array

Try this

@users = @search.where("users.id = ?", params[:id])
@user = @users.nil? ? @foundusers.first : @users.first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM