Ramy
Ramy

Reputation: 21261

ActiveModel::AttributeError rails 3

i'm a complete Rails newbie and would appreciate any assistance.

I'm currently getting an error when I try to select the distinct sources from my Users table. So, the SQL query would be pretty straight forward. Something like this:

select distinct source from users;

or

select source from users group by source;

the problem is that in my ".erb" file, i have this:

<%= f.select :source, User.find(:all, :select => "source") %>

i've also tried this:

<%= f.select :source, User.select(:source).group(:source) %>

the problem is i'm getting this message:

missing attribute: first_name

obviously, i'm not selecting first_name, but i have noticed that in my "to_s" method that someone else wrote, the return value is

full_name.blank? ? email.gsub(/(.).*(.)@/,'\1..\2@').gsub(/@(.).*(.)\.([^.]+)/,'@\1..\2.\3') : full_name

where:

def full_name
  "#{self.first_name} #{self.last_name}".strip
end

so, it seems that somewhere, something is implicitly calling "to_s" and is not finding the first_name attribute.

outside of modifying my to_s method (which is used widely in the code base) how can I simply select a list of distinct sources from the User table?

Upvotes: 1

Views: 320

Answers (2)

Mr_Nizzle
Mr_Nizzle

Reputation: 6714

The problem is that using the select method the query will only return the source column of the table and for the select you'll need at least two parameters, what you could do is something like:

<%= f.select :source, User.find(:all,:select=>"source",:group=>"source").map {|u| [u.source,u.source]} %>

Upvotes: 1

sparrovv
sparrovv

Reputation: 7774

Ideally I would create source model that has_many users, but if you need quick solution:

class User < ActiveRecord::Base
  def self.sources
     all.group(:source).map(&:source)
  end
end

in controller:

@sources = User.sources

form:

<%= f.select :source, @sources.map{|s| [s,s]} %>

This should work.

Upvotes: 1

Related Questions