[英]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.我想在活动记录 object 上调用属性的 getter 方法并让它返回字符串集合,而不是自定义对象的集合。
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.我不想定义“FavouriteSongTitles”class 并执行“has_many”和“belongs_to”,因为没有与这些值相关的行为。
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:在我的想象中,一些连接语法会像这样 go :
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 中的 to_s 方法:
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.我不知道如何让 AR 了解没有关联 model class 的表。
Another approach might be the serialize (http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize) method:另一种方法可能是序列化(http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize)方法:
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.