Anh*_* Vo 4 ruby json delegates ruby-on-rails
我在 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
Run Code Online (Sandbox Code Playgroud)
现在我使用淘汰赛来管理客户端的帖子,所以我必须使用 posts.to_json 将我的对象设置为 json。这些 JSON 对象没有全名属性。我尝试使用 user.to_json,这些对象也没有该属性。那么如何使委托序列化为 JSON?
由于 fullname 是某种意义上的虚拟属性:
轨道 2:
posts.to_json(:method => %w(fullname))
user.to_json(:method => %w(fullname))
Run Code Online (Sandbox Code Playgroud)
轨道 3:
posts.to_json(:methods => %w(fullname))
user.to_json(:methods => %w(fullname))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2450 次 |
最近记录: |