我有一个会议桌,其中有一个请求者(用户),其属性为birthyear。
在终端我可以做Meeting.find(1).requestor.birthyear
但在会议控制器中,它显示no such column: requestor.birthyear
我尝试在meetings_params中添加类似users_attributes: [:birthyear]
的内容,但它没有任何区别。
我错过了什么?
以下是完整文件: 会议控制员
def community
if current_user.birthyear != nil
@meeting_requests = Meeting.where('meeting_time >= ? AND requestee_id IS ? AND status = ? AND (requestor.birthyear <= ? AND requestor.birthyear >= ?)', Date.today, nil, "Active", current_user.birthyear + 10, current_user.birthyear - 10).order('meeting_time asc')
end
end
会议模式
class Meeting < ApplicationRecord
belongs_to :requestor, class_name: "User"
belongs_to :requestee, class_name: "User"
end
错误:
SQLite3::SQLException: no such column: requestor.birthyear: SELECT "meetings".* FROM "meetings" WHERE (meeting_time >= '2017-03-06' AND requestee_id IS NULL AND status = 'Active' AND (requestor.birthyear <= 1944 AND requestor.birthyear >= 1924)) ORDER BY meeting_time asc
如果您需要更进一步,请告诉我们 - 提前感谢!
更新
尝试加入查询中的表,但对此并不太了解。我在尝试:
@meeting_requests = Meeting.where('meeting_time >= ? AND requestee_id IS ? AND status = ? ', Date.today, nil, "Active").order('meeting_time asc').joins("INNER JOIN users on requestor.birthyear >= current_user.birthyear + 10")
但得到:
ActionView::Template::Error (SQLite3::SQLException: ambiguous column name: status: SELECT "meetings".* FROM "meetings" INNER JOIN users on requestor.birthyear >= current_user.birthyear + 10 WHERE (meeting_time >= '2017-03-07' AND requestee_id IS NULL AND status = 'Active' ) ORDER BY meeting_time asc):
***** UPDATE ***** 我发布了另一个问题来获取语法。如果它有助于任何人: Rails: Two 'where' queries - each works individually, but not together
答案 0 :(得分:2)
requestor
和requestee
是Rails关联。这意味着Rails了解如何从会议中获取requestor
...
但是 - 您的数据库不知道requestor
是什么。所以你不能像在这里一样把它放在SQL查询的字符串部分中:
AND (requestor.birthyear <= ? AND requestor.birthyear >= ?)'
相反,您需要使用连接将这些连接添加到查询中,然后找出rails如何命名它们以便从中访问列。