我想在一个索引方法中呈现json,该方法连接Rails中与外键相关的表的数据。我有一个将user_id作为外键的模型。
class Batch < ActiveRecord::Base
belongs_to :user
然后我渲染该表并公开 user_id 字段。
def index
panels = Batch.where("user_id = #{current_user.id} or (user_id <> #{current_user.id} and public_panel = true)")
render json: panels, only: [:id, :description, :name, :public_panel, :updated_at, :user_id], root: false
end
我想要的是以某种方式公开用户名,该名称位于用户模型上。即: user_id.user_name
修改
从阅读文档中,我认为我需要使用 include ,但也希望为其中一个字段添加别名。我在两个表中都有一个名为 name 的字段。
此包含
有问题 def index
panels = Batch.include([:users]).where("user_id = #{current_user.id} or (user_id <> #{current_user.id} and public_panel = true)")
render json: panels, only: [:id, :name, :description, :public_panel, :updated_at, :user_id], root: false
end
EDIT2
谢谢@Paritosh Piplewar ......我的语法错误了。更复杂的是,我所追求的字段是 user.name ,而不是 user.user_name 。这会与 batches.name 冲突,所以我需要别名。
Started GET "/api/batches" for 10.0.2.2 at 2014-08-13 15:39:03 +0200
SyntaxError (/home/assay/assay/app/controllers/api/batches_controller.rb:11: syntax error, unexpected tLABEL
user: { only: :first_name },
^
/home/assay/assay/app/controllers/api/batches_controller.rb:11: syntax error, unexpected ',', expecting keyword_end
user: { only: :first_name },
^
/home/assay/assay/app/controllers/api/batches_controller.rb:12: syntax error, unexpected ',', expecting keyword_end):
编辑3
原来的问题已经回答,但是json返回的是这样的
data: [{"id"=>1306, "updated_at"=>Wed, 13 Aug 2014 12:37:23 UTC +00:00, "description"=>"asc", "user_id"=>1, "public_panel"=>true, "user"=>{"name"=>"Joe Bloggs"}}, {"id"=>1307,
这个位导致我的Angular.js前端出现问题。
"user"=>{"name"=>"Joe Bloggs"}}
答案 0 :(得分:2)
我认为你的意思是user.user_name
这就是你如何做到的
def index
panels = Batch.where("user_id = #{current_user.id} or (user_id <> #{current_user.id} and public_panel = true)")
data = panels.as_json(include:
{user: { only: :name }},
only: [:id, :description, :public_panel, :updated_at, :user_id],
root: false)
render json: data
end
答案 1 :(得分:1)
对于更复杂的json视图而不仅仅是单个模型,我会告诉你使用jbuilder。 Jbuilder现在是rails框架的一部分。
就像
一样简单json.array @panels do |panel|
panel.(panel,
:id,
:description,
:public_panel,
:user_id,
:updated_at
)
json.user panel.user.user_name
end
答案 2 :(得分:1)
您可以定义自定义方法并执行此操作。像这样的东西
class Batch < ActiveRecord::Base
belongs_to :user
def user_name
user.name
end
end
现在,在控制器中你可以简单地执行此操作
def index
panels = Batch.where("user_id = ? or (user_id <> ? and public_panel = true)", current_user.id, current_user.id)
data = panels.as_json(methods: :user_name,
only: [:id, :description, :public_panel, :updated_at, :user_id, :user_name],
root: false)
render json: data
end