1

I'm creating an object:

artist = Artist.create(:name => "Jbeebs",
                       :genre => "bestmusicever", 
                       :plays => "toomany")

I would like the variable artist to only have the name and genre attributes so I can return artist.name and artist.genre, but nothing else.

Is there something like select for creates?

I have an array of artists and would like to return only name and genre of each when I'm outputting JSON.

4

2 回答 2

2

You can do this by overloading the to_json method in Artist

def to_json(options = {})
  { name: name, genre: genre }.to_json(options)
end

When you cast the method to JSON, it will appear as a JSON object without :plays included.

于 2012-10-26T22:03:58.713 回答
0

When you output the json, just parse through your artists and create a new object to convert to json:

json_array = []
artists.collect{|artist| json_array << {name: artist.name, genre: artist.genre}}
json_array.to_json

Otherwise if you always want artists output in json with just those two attributes, use Deefour's answer.

于 2012-10-26T22:06:57.303 回答