简体   繁体   中英

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.

Code in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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