开发者

Is there a way to assign a collection of primitives (eg String, Fixnum, rather than custom Objects) to an object using ActiveRecord in Rails?

I would like to call an attribute's getter method on an active record object and have it return a collection of strings, rather than a collection of custom defined objects.

eg.

person.favourite_song_titles => ["Somewhere over the rainbow","Beat it","Poker face"]

NOT

person.favourite_song_titles => [#FavouriteSongTitle name: "Somewhere over the rainbow",#FavouriteSongTitle name:"Beat it",#FavouriteSongTitle name:"Poker face开发者_开发知识库"]

I don't want to have to define a "FavouriteSongTitles" class and do "has_many" and "belongs_to" as there is no behaviour associated with these values.

Ideally I'd like tables:

create_table "people" do | t |
 #some attributes defined here
end

create_table "favourte_song_titles" | t |
  t.column "person_id", :integer
  t.column "value", :string
end

And some joining syntax that in my imagination would go like this:

Class Person < ActiveRecord::Base
  has_many :favourite_song_titles, :class_name => "String", #some config to tell active record which table/column to use
end


Why not just add a new method? You won't have to fight the framework so much.

class Person < ActiveRecord::Base
  has_many :song_titles

  def fav_song_titles
    song_titles.map(&:name)
  end
end

Another option depending on how you are using it is to override the to_s method in the song title class:

class SongTitle < AR:Base
  def to_s
    name
  end
end

The last can be handy in views, but might not be quite what you are looking for.


I don't know of a way to have AR know about a table without an associated model class.

Another approach might be the serialize (http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize) method:

create_table "people" do | t |
  #some attributes defined here
  t.text :favourite_song_titles
end

Class Person < ActiveRecord::Base
  serialize :favourite_song_titles
  attr_accessor :favourite_song_titles
end

And you would be able to:

person.favourite_song_titles = ["Somewhere over the rainbow","Beat it","Poker face"]
person.save
person.reload
person.favourite_song_titles #  ["Somewhere over the rainbow","Beat it","Poker face"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜