【问题标题】:Ruby on Rails Form for has_many relationship用于 has_many 关系的 Ruby on Rails 表单
【发布时间】:2012-08-31 16:02:12
【问题描述】:

我有用户在注册时需要回答一些问题。用户通过 Answers 连接表有_many Questions。我只是想弄清楚如何在 Users#new 操作上创建表单。我正在使用 simple_form。这是我的数据库架构:

ActiveRecord::Schema.define(:version => 20120831144008) do

  create_table "answers", :force => true do |t|
    t.integer  "user_id"
    t.integer  "question_id"
    t.text     "response"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  add_index "answers", ["user_id", "question_id"], :name => "index_answers_on_user_id_and_question_id"

  create_table "questions", :force => true do |t|
    t.string   "title"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "users", :force => true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
  end

end

所以在 users#new 页面上,我正在遍历问题标题,并且需要在每个问题下方创建一个文本区域并创建它。到目前为止,这是我所拥有的表格,它不起作用,可能对解决方案没有太大帮助。

<%= simple_form_for(@user) do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.input :email %>
  <%= f.input :phone %>
  <%= f.input :organization %>
  <%= f.input :primary_contact %>
  <%= f.association :answers, collection: @questions %>
  <% @questions.each do |question| %>
    <div>
      <strong><%= question.title %></strong>
      <%= text_field_tag 'questions[]' %>
    </div>
  <% end %>
  <%= f.button :submit %>
<% end %>

解决方案

我能够让它工作,不确定这是否是绝对正确的方法,但它并不完全丑陋。在我的控制器中,我有 @user.answers.build,在我的 simple_form 中,我遍历问题,并创建一个填写了所需数据的答案字段。

  <% Question.all.each do |question| %>
    <%= f.simple_fields_for :answers do |a| %>
      <div>
        <strong>
          <%= question.title %>
        </strong>
        <%= a.hidden_field :question_id, value: question.id %>
        <%= a.input :response, label: false %>
      </div>
    <% end %>
  <% end %>

【问题讨论】:

    标签: ruby-on-rails forms relationship has-many-through simple-form


    【解决方案1】:

    我相信你需要这样做:

    <%= simple_fields_for @questions.each do |question| %>
    

    确保您获得嵌套的表单字段。

    【讨论】:

    • 嘿,真的不能很好地遵循这个逻辑。我用一个可行的解决方案更新了我的问题,但可能不是最漂亮的。感谢回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2012-06-12
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    相关资源
    最近更新 更多