Skip to main content
 首页 » 编程设计

ruby-on-rails之如何根据检索到的字段计算字段并合并到 Rails 中的 JSON 中

2025年12月25日24lhb25

我有一个 Controller 方法,它根据用户 ID 从一个表中检索所有数据。我想为该用户简单添加该表中的两个整数字段,并将其作为返回的 JSON 的一部分。这是我到目前为止所拥有的:

def show 
     @user = User.find(params[:id]) 
    respond_to do |format| 
      # Here we need to remove the layout because the request 
      # is done via ajax and the layout is already loaded. 
 
      format.json {  render json: @user.to_json }  
    end 

我想要添加在一起以形成这个新字段的字段是“Score1”和“Score2”。我假设我必须做类似 @user.OverallScore = @user.Score1 + @user.Score2

的事情

请您参考如下方法:

您可以在User模型中定义实例方法score_sum

def score_sum 
  self.Score1 + self.Score2 
end 

并在 Controller 中使用@user.to_json(:methods => [:score_sum])