【问题标题】:Rails can have several fields_for in a form?Rails 在一个表单中可以有几个fields_for?
【发布时间】:2014-11-29 09:33:00
【问题描述】:

两个模型是belongs_to 和has_many 关联。如:

class User < ActiveRecord::Base
  has_many :user_infos
end 

class UserInfo < ActiveRecord::Base
  belongs_to :users
end

所以,我构建了一个表单,我想创建一个包含多个 user_infos 的用户帐户。 我可以在使用嵌套表单的表单中执行此操作吗?

但是如果我不确定有多少个 :user_infos 怎么办?

【问题讨论】:

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


    【解决方案1】:

    是的,你可以。不过,这取决于您要创建多少 user_infos。例如:

    在控制器的new 方法中:

    def new
      @user = User.new
      3.times{ @user.user_infos.build }
    end
    

    在您的表单中:

    <%= form_for @user do |f| %>
      <%= f.text_field :email %>
      <%= f.fields_for :user_infos do |uif| %>
         <%= uif.text_field :name %>
      <% end %>
    <% end %>
    

    这将在带有文本字段名称的表单上创建 3 个user_infos

    【讨论】:

    • 但是我不知道应该添加多少user_infos。我想让用户决定他们要添加多少用户信息。
    • @rocLv :这可以通过 jQuery 完成。查看这两个 railscast Nested Model Form part - 1Nested Model Form part - 2 了解更多详情。
    • 对于 Rails 4.2,我使用的是 ActionForm。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2013-06-15
    • 2015-01-16
    相关资源
    最近更新 更多