我正在尝试学习如何在Rails5中编写作用域。
我有一个用户模型和一个提案模型。这些关联包括:
用户:
has_many :proposals建议:
belongs_to :user在我的提案模型中,我试图弄清楚如何编写一个范围来查找属于创建提案的用户的提案。
我正在尝试:
scope :proponent, -> { where(user_id: user.id) }我已经尝试了上百万个版本,但是我找不到一个可以工作的。
此特定尝试会产生以下错误:
2.3.1p112 :001 > Proposal.proponent
NameError: undefined local variable or method `user' for Proposal (call 'Proposal.connection' to establish a connection):Class我也尝试过:
scope :proponent, -> { where('proposal.user_id = ?', user.id) }我从这次尝试中得到的错误是:
undefined local variable or method `user' for #<Class:0x007fd3600eb038>我不知道这个错误消息是否意味着我在尝试中第一次还是第二次写“user”是不正确的。我不知道“叫'Proposal.connection‘是什么意思”。
是否有人能看到我需要做些什么才能检查proposals表以查找属于特定用户的proposals表?
发布于 2016-12-17 09:02:12
在调用作用域时,需要将user或user_id作为参数传入。您可以这样定义它:
scope :proponent, ->(user){ where(user_id: user.id) }或
def self.proponent(user)
where user_id: user.id
end它们实际上是一回事。
然后叫它:
Proposal.proponent(user)
# => returns a list of proposals for the specific user请注意,这与说
proposal = Proposal.find_by(...)
proposal.user.proposalshttps://stackoverflow.com/questions/41194374
复制相似问题