之后Post.all,我试图返回一个带有自定义属性的帖子对象的 JSON 数组。这是我所拥有的:
@posts = Post.includes(:profil).page(params[:page]).order('created_at DESC')
render json: @posts.to_json(:include => :profil,
:methods => [:image_url, :vote_modificator])
此方法正确返回一个帖子列表,包括Profil一个自定义属性image_url。我有一个模型Vote,它属于Profil和Post:
class Vote < ActiveRecord::Base
attr_accessible :value
belongs_to :profil
belongs_to :post
end
我想在每个帖子中插入Vote与其自身相对应的值,并在如下current_user定义application_controller.rb:
def current_user
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end
helper_method :current_user
我尝试在 中添加一个方法to_json,但模型中定义的方法无法访问此帮助程序。有什么办法可以解决我的问题吗?