![](/img/trans.png)
[英]Using rails associations for models (undefined method `has_one')
[英]Ruby on Rails: Undefined Method Error with has_one associations
出于某种原因,我得到了针对某些查询的NoMethodError,该查询实际上在rails控制台中有效。
index.html.erb中的代码
@requests.first.acceptance
这是我的错误
undefined method `acceptance' for #<ActiveRecord::Relation::ActiveRecord_Relation_Arrangement:0x000000042ceeb8>
这些是我的模块。
class Arrangement < ActiveRecord::Base
belongs_to :acceptance
belongs_to :request
belongs_to :offer, inverse_of: :arrangements
end
class Acceptance < ActiveRecord::Base
belongs_to :user, inverse_of: :acceptances
has_one :arrangement
end
class Request < ActiveRecord::Base
belongs_to :user, inverse_of: :requests
has_one :arrangement
end
这是我的控制器
def index
@requests = Array.new
for request in current_user.requests do
@requests << Arrangement.where("request_id = ?", request.id)
end
@acceptances = Array.new
for acceptance in current_user.acceptances do
@acceptances << Arrangement.where("acceptance_id = ?", acceptance.id)
end
end
我无法弄清楚我在这里做错了什么。 一切都可以在控制台中运行,但不能在浏览器中运行。
Arrangement.where("request_id = ?", request.id)
返回类似数组的关系对象,该对象可能包含多个记录,而不仅仅是一个记录。
但是,在控制器的这一行上
@requests << Arrangement.where("request_id = ?", request.id)
您正在将关系添加到数组中,以便
@requests.first.acceptance
返回关系,而不是第一条记录。
解决此问题的一种方法是在您的控制器中执行此操作:
@requests = Array.new
for request in current_user.requests do
@requests << Arrangement.where("request_id = ?", request.id).first
end
解决了
我在控制器的@requests数组中传递了一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.