【问题标题】:How do I make a custom belongs_to association with a different foreign_key display as the association name when rendering as JSON?当呈现为 JSON 时,如何使用不同的 foreign_key 显示自定义的 belongs_to 关联作为关联名称?
【发布时间】:2013-01-09 23:15:58
【问题描述】:

我对 Rails 还很陌生,并且在我的 Champion 模型上通过 belongs_to 建立了 5 个关联,这些关联连接到 Ability 模型,该模型有一个 has_one 关联回 Champion 模型。

这 5 个关联使用与关联名称和“_id”相匹配的外键。当我去渲染页面时,我看到“_id”值显示为整数,但希望这些显示为实际记录。因此,它不会只显示一个整数,而是会显示完整的能力记录及其所有字段。

这是我的 Champion.rb 模型:

class Champion < ActiveRecord::Base
  attr_accessible :q_id,
                  :w_id,
                  :e_id,
                  :r_id,
                  :passive_id

  belongs_to :q, :class_name => "Ability", :foreign_key => "q_id"
  belongs_to :w, :class_name => "Ability", :foreign_key => "w_id"
  belongs_to :e, :class_name => "Ability", :foreign_key => "e_id"
  belongs_to :r, :class_name => "Ability", :foreign_key => "r_id"
  belongs_to :passive, :class_name => "Ability", :foreign_key => "passive_id"
end

还有ability.rb模型:

class Ability < ActiveRecord::Base
  has_one :champion
end

以及显示模型的控制器:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def show_all
    load_models

    respond_to do |format|
      format.json { render :json => { "champions" => @champions } }
    end
  end

  protected
  def load_models
    @champions = Champion.all
  end
end

那么我该如何设置,让 JSON 显示“q”、“w”、“e”、“r”和“passive”而没有“_id”,并显示整个能力记录?现在它只显示包含 id 的实际数据库字段,但不显示我想要的记录。任何帮助表示赞赏!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 json rails-activerecord


    【解决方案1】:

    最简单的方法是这样的:

    respond_to do |format|
      format.json { render :json => @champions.to_json(:include => {:q => {}, :w => {}}) }
    end
    

    不过,我可能会建议您查看 RABL 之类的内容。它将使处理这些更复杂的 json 响应变得更清晰。上面有一个很好的 Railscast here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多