简体   繁体   English

Rails 4:嵌套属性未显示在窗体上

[英]Rails 4: Nested Attributes Not Showing on Form

I am trying to run through a simple nested_attributes exercise, where a question has many answers (how like life is that?). 我试图通过一个简单的nested_attributes练习来完成,其中一个问题有很多答案(生活怎么样?)。 I can't get the answers field to show up in either the 'new' or the 'edit' actions. 我无法在“新”或“编辑”操作中显示答案字段。 As far as I can tell, I'm following the specs precisely. 据我所知,我严格遵守规范。 Clearly, this is not the case. 显然,事实并非如此。 Any pointers appreciated, thanks. 任何指针表示赞赏,谢谢。

Models 楷模

# question.rb
has_many :answers
accepts_nested_attributes_for :answers

# answer.rb
belongs_to :question

View 视图

# _form.html.erb
<%= form_for(@question) do |f| %>
  ...
  <div class="field">
    <%= f.label :content, 'Question' %><br>
    <%= f.text_field :content %>
  </div>

  <div class="field">
        <% f.fields_for :answers do |ff| %>
        <%= ff.label :content, 'Answer' %><br>
        <%= ff.text_field :content %>
        <% end %>
  </div>
  ...
<% end %>

Controller 控制者

# questions_controller.rb
def new
  @question = Question.new
  @question.answers.build
end

def edit
end

def create
  @question = Question.new(question_params)

  respond_to do |format|
    if @question.save
      format.html { redirect_to @question, notice: 'Question was successfully created.' }
      format.json { render :show, status: :created, location: @question }
    else
      format.html { render :new }
      format.json { render json: @question.errors, status: :unprocessable_entity }
    end
  end
end

private 

def question_params
  params.require(:question).permit(:content, answer_attributes: [:id, :content, :question_id] )
end

使用<%= ,而不是<% ,否则field_for Form Builder的结果输出将不会输出到表单。

<%= f.fields_for :answers do |ff| %>

Now I just need to figure out why the nested attribute (the answer) isn't saving to the database. 现在,我只需要弄清楚为什么嵌套属性(答案)没有保存到数据库中。

Extending @Dylan Markow 's answer. 扩展@Dylan Markow的答案。

Since it is has_many answers ,it should be answers_attributes instead of answer_attributes in your question_params method. 由于它是has_many answers ,因此在您的question_params方法中应为answers_attributes而不是answer_attributes

def question_params
  params.require(:question).permit(:content, answers_attributes: [:id, :content, :question_id] )
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM