【问题标题】:Create multiple new records from checkboxes in form using nested attributes in Rails使用 Rails 中的嵌套属性从表单中的复选框创建多个新记录
【发布时间】:2019-04-16 20:10:07
【问题描述】:

如果在复选框列表中选中多个位置,我正在尝试创建一个联系人表单,该表单创建一个联系人记录和可能的多个位置记录。如果不检查所有位置记录,我想创建然后销毁它们。不过我认为这不是最佳选择。

我在模型中使用多对多关系。

这就是他们现在的样子:

联系人.rb

class Contact < ApplicationRecord
has_many :contact_locations, dependent: :destroy
has_many :locations, through: :contact_locations
accepts_nested_attributes_for :contact_locations, allow_destroy: true, reject_if: :empty_location?

private
def empty_location?(att)

att['location_id'].blank?

end

end

位置.rb

class Location < ApplicationRecord
has_many :locations, dependent: :destroy
has_many :contacts, :through => :contact_locations
has_many :contact_locations
end

contact_location.rb

class ContactLocation < ApplicationRecord
belongs_to :location
belongs_to :contact
end

contacts_controller.rb

def new
@contact = Contact.new
@locations = Location.all
4.times {@contact.contact_locations.new}
end

private

def contact_params
params.require(:contact).permit(:name, :phone, ..., contact_locations_attributes: [:location_ids])
end

new.html.rb

<%= form_with model: @contact do |f| %>
  ...
<%= @locations.each do |location| %>
<%= f.fields_for :contact_locations do |l| %>
<%= l.check_box :location_id, {}, location.id, nil %><%= l.label location.name %>
<% end %>
<% end %>
 ...
<% end %>

有没有人可以让它正常工作? 我正在开发 Ruby 2.5.1 和 Rails 5.2.1。

非常感谢。

【问题讨论】:

    标签: ruby-on-rails checkbox nested-attributes


    【解决方案1】:

    我认为您的解决方案是表单对象模式。

    你可以有这样的东西:

    <%= form_for @user do |f| %>
      <%= f.email_field :email %>
    
      <%= f.fields_for @user.build_location do |g| %>
        <%= g.text_field :country %>
      <% end %>
    <% end%>
    

    并将其转换为更易读的内容,允许您实例化注册对象内的位置,检查复选框的值。

    <%= form_for @registration do |f| %>
      <%= f.label :email %>
      <%= f.email_field :email %>
    
      <%= f.input :password %>
      <%= f.text_field :password %>
    
      <%= f.input :country %>
      <%= f.text_field :country %>
    
      <%= f.input :city %>
      <%= f.text_field :city %>
    
      <%= f.button :submit, 'Create account' %>
    <% end %>
    

    您将在此处了解如何应用该模式:https://revs.runtime-revolution.com/saving-multiple-models-with-form-objects-and-transactions-2c26f37f7b9a

    【讨论】:

      【解决方案2】:

      我最终使它与 Kirti 对以下问题的建议一致: Rails Nested attributes with check_box loop

      事实证明,我需要对表单的 fields_for 标记进行一些小调整。

      非常感谢您的帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2019-05-23
        • 1970-01-01
        相关资源
        最近更新 更多