[英]Rails: How to show an attribute from a parent model in the child new action?
[英]Show child as parent in model - Rails
我正在使用Rails 4.1.4
在那我有一個模型:
class FormQuestion < ActiveRecord::Base
belongs_to :form_parent_question, :foreign_key => 'form_parent_question_id', :class_name => 'FormQuestion'
has_one :form_child_question, :foreign_key => 'form_parent_question_id',
accepts_nested_attributes_for :form_child_question
end
如您所見,這里有一個父子問題。
當我執行FormQuestion.all.to_json時,子問題出現在渲染的父問題內部。
有沒有辦法讓所有問題排成陣列?
電流響應
{"form_questions":[
{
"id":1,
"form_child_question": {
"id":2,
"form_child_question": null
}
}
]}
我想要實現但無法做到的回應:
{"form_questions":[
{
"id":1,
"form_parent_question_id": null
},
{
"id":2,
"form_parent_question_id": 1
},
]}
只是用這個
FormQuestion.all.map{|f| {id: f.id, form_parent_question_id: f.form_parent_question_id } }
這將給您您期望的結果。
如果要構建API,也可以使用序列化程序。 您可以使用的寶石是active_model_serializers
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.