Rails activerecord 元搜索未定义方法

发布于 2024-11-06 23:06:32 字数 763 浏览 4 评论 0原文

我是 Rails 新手,需要您的帮助来解决一个简单的问题。

当我运行此代码时:

@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

我收到以下错误语句: undefined method `company_id' for #

我不明白,因为数据库上的查询是正确的 (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'))

并且该用户的 company_id 不为空。

当我输入 put @user.name 时,它​​没有给我用户名,而是给我“用户”

非常感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

昵称有卵用 2024-11-13 23:06:32

虽然您的数据库“users”表有一个名为“company_id”的列,但User模型有一个名为“company”的属性。

尝试

除非@user.company_id.nil?
@company = Company.find(@user.company.id)
结尾

Although your database 'users' table has a column called 'company_id' the User model has a property just called 'company'.

Try

unless @user.company_id.nil?
@company = Company.find(@user.company.id)
end

柒七 2024-11-13 23:06:32

感谢您的帮助。实际上,我通过将模型名称@user更改为@myuser来解决这个问题。我没有改变任何其他东西并且它有效。我的猜测是该问题是由于 Devise 插件造成的,但这只是猜测......

干杯。

thanks for your help. Actually, I solved the issue by changing the model name @user into @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...

Cheers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文