absolutskyy
absolutskyy

Reputation: 567

Accessing attributes via Rails relations

I have a Position model for which I have a scope defined:

scope :default, where('is_default = ?', 1)

Idea being that I want to know which is the default position. I can do something like: @profile.positions.default and this returns an activerecord relation and the default position record. The issue is that now that I have the default record, I need to access other attributes of Positions such as title..

@profile.positions.default.title 

but the above returns an error: NoMethodError: undefined method `title' for #

Any clues? Thanks.

Upvotes: 0

Views: 76

Answers (2)

Damien
Damien

Reputation: 27463

class Profile < ActiveRecord::Base
  has_many :positions
  has_one :default_position, :class_name => 'Position', 
                             :conditions => ['is_default = ?', true]
end

Then

@profile.default_position.title

Upvotes: 0

Dylan Markow
Dylan Markow

Reputation: 124419

A scope turns a collection of objects, not a single object, so you're trying to call title on an array of ActiveRecord results.

You probably want something like this:

@profile.positions.default.first.title

Or if you always want just one record, you may switch from a scope to a class method:

def self.default
  where('is_default = ?', 1).first
end

Upvotes: 1

Related Questions