我在Rails中有3个模型:User,UserProfile和Post
这样的事情:
class Post < ActiveRecord::Base
attr_accessible :content, :post_type
belongs_to :user
delegate :fullname, :to => :user, :prefix => "author"
end
class User < ActiveRecord::Base
has_many :posts
has_one :user_info
delegate :fullname, :to => :user_info
end
class UserInfo < ActiveRecord::Base
attr_accessible :avatar, :fullname, :birthday, :nickname, :gender, :about
belongs_to :user
end
现在我使用knockout来管理客户端的帖子所以我必须使用posts.to_json将我的对象设置为json。这些JSON对象没有属性fullname。我尝试使用user.to_json,这些对象也没有该属性。那么如何才能使委托序列化为JSON?
答案 0 :(得分:4)
因为fullname是某个意义上的虚拟属性:
Rails 2:
posts.to_json(:method => %w(fullname))
user.to_json(:method => %w(fullname))
Rails 3:
posts.to_json(:methods => %w(fullname))
user.to_json(:methods => %w(fullname))