【问题标题】:Ruby on Rails creation of record with nested forms and join tableRuby on Rails 使用嵌套表单和连接表创建记录
【发布时间】:2015-06-17 05:30:27
【问题描述】:

我正在尝试使用连接表中捕获的多对多关系(调查和问题之间)创建记录。我希望用户能够创建一个调查问卷,其中包含一个表单中的问题,但问题不会出现。

[编辑:RAJ修改后,只显示一个问题,不保存到数据库中。]

[编辑:Rails 版本 4.2.0,ruby 版本 2.2.1p85,物有所值]

[编辑:按照RAJ 的建议,在部分表单中添加了“=”]

问题模型:

class Question < ActiveRecord::Base
    has_many :survey_questions
    has_many :surveys, :through => :survey_questions
end

调查模型:

class Survey < ActiveRecord::Base
    has_many :survey_questions
    has_many :questions, :through => :survey_questions

    accepts_nested_attributes_for :survey_questions
end

SurveyQuestion 连接表:

class SurveyQuestion < ActiveRecord::Base
    belongs_to :survey
    belongs_to :question
    accepts_nested_attributes_for :question
end

/surveys/_form.html.erb 部分:

<%= form_for @survey do |f|%>
    <h3>The Survey Itself</h3>
    <%= f.label :title %>
    <%= f.text_field :title %> <br/>

    <h3>Questions:</h3>
    <%= f.fields_for :questions do |builder| %>
    <p>
        <%= builder.label :question_text, "Question Text" %><br />
        <%= builder.text_field :question_text %>
    </p>
    <% end %>

    <%= f.submit "Submit" %>
<% end %>

/surveys/new.html.erb 视图:

<h1>New Survey</h1>
<%= render :partial => "form" %>

最后是 SurveysController:

class SurveysController < ApplicationController
  # I have a few other actions here, like list, edit, delete and so forth

  def new
    @survey = Survey.new

    3.times do
        question = @survey.questions.build
        survey_question_combo = @survey.survey_questions.build
  end

  def create
    @survey = Survey.new(params[:survey].permit(:title))
    if @survey.save
        redirect_to :action => "show", :id => @survey
    else
        render :action => "new"
    end
  end
end

问题是,当我创建一个新的调查时,HTML 最多显示 h3“问题”,但没有低于它。我该如何纠正这个问题?

【问题讨论】:

    标签: ruby-on-rails model nested-forms jointable


    【解决方案1】:

    在您的_form 部分中,您需要在f.fields_for 之前添加= 以便它显示在页面上。

    <%= f.fields_for :questions do |builder| %>
      <p>
        <%= builder.label :question_text, "Question Text" %><br />
        <%= builder.text_field :question_text %>
      </p>
    <% end %>
    

    此外,您可以将new.html.erb 更新为:

    <h1>New Survey</h1>
    <%= render :partial => "form" %>
    

    【讨论】:

    • 谢谢。这确实有助于显示一个问题文本,但不是我想要的 10.times { ... } 中的 10 个
    【解决方案2】:

    虽然我仍然不确定上面的问题是什么,但我找到了一个很好的教程here。它使用了一个名为 cocoon 的 gem。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      相关资源
      最近更新 更多