简体   繁体   English

Ruby on Rails:has_one关联的未定义方法错误

[英]Ruby on Rails: Undefined Method Error with has_one associations

For some reason I'm getting an NoMethodError for some query, which actually works in the rails console. 出于某种原因,我得到了针对某些查询的NoMethodError,该查询实际上在rails控制台中有效。

Code in index.html.erb index.html.erb中的代码

@requests.first.acceptance

This is my Error 这是我的错误

undefined method `acceptance' for #<ActiveRecord::Relation::ActiveRecord_Relation_Arrangement:0x000000042ceeb8>

These are my Modules. 这些是我的模块。

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

This is my Controller 这是我的控制器

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

I can't figure out what I've done wrong here. 我无法弄清楚我在这里做错了什么。 Everything works in the console, though not in the browser. 一切都可以在控制台中运行,但不能在浏览器中运行。

Arrangement.where("request_id = ?", request.id)

Returns an array-like relation object which may contain multiple records, not just a single record. 返回类似数组的关系对象,该对象可能包含多个记录,而不仅仅是一个记录。

However, on this line in your controller 但是,在控制器的这一行上

@requests << Arrangement.where("request_id = ?", request.id)

You're adding the relation to your array, so that 您正在将关系添加到数组中,以便

@requests.first.acceptance

Returns the relation, instead of the first record. 返回关系,而不是第一条记录。

One way to fix this is to do this in your controller: 解决此问题的一种方法是在您的控制器中执行此操作:

@requests = Array.new
for request in current_user.requests do 
    @requests << Arrangement.where("request_id = ?", request.id).first
end

Solved 解决了

I was passing an array in the @requests array in my controller. 我在控制器的@requests数组中传递了一个数组。

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

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