简体   繁体   English

Rails ActiveRecord元搜索未定义方法

[英]rails activerecord metasearch undefined method

I'm new to rails and need your help for what should be a simple problem. 我是Rails的新手,需要您的帮助才能解决一个简单的问题。

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 # 我收到以下错误声明:#的未定义方法`company_id'

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')) 我不明白,因为数据库上的查询是正确的(SELECT users。* FROM users LEFT OUTER JOIN Companies ON companies.id = users.company_id WHERE(((((users.firstname LIKE'%s%'OR users.lastname LIKE'% s%')或companies.name像'%s%'))和(users.id ='11'))

and the company_id for this user is not empty. 并且该用户的company_id不为空。

When I type puts @user.name, instead of giving me the user name, it gives me 'User' 当我键入puts @ user.name时,没有给我用户名,而是给了我'User'

Many thanks for your help. 非常感谢您的帮助。

Although your database 'users' table has a column called 'company_id' the User model has a property just called 'company'. 尽管您的数据库 “用户”表中有一个名为“ company_id”的列,但用户模型具有一个仅称为“公司”的属性。

Try unless @user.company_id.nil? 尝试除非@ user.company_id.nil? @company = Company.find(@user.company.id) end @company = Company.find(@ user.company.id)结束

thanks for your help. 谢谢你的帮助。 Actually, I solved the issue by changing the model name @user into @myuser. 实际上,我通过将模型名称@user更改为@myuser来解决了该问题。 I didn't change anything else and it works. 我没有进行任何其他更改,并且可以正常工作。 My guess is that the issue is due to the Devise plug-in but it's just a guess... 我的猜测是该问题是由于Devise插件引起的,但这只是一个猜测...

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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