简体   繁体   中英

Rails nested attributes with existing records

I'm trying to deal with nested attributes with the usual way:

Model:

class InventoryItem < ApplicationRecord
  belongs_to :location

  accepts_nested_attributes_for :location
end

Form:

  <div class="field">
    <%= form.fields_for :location do |location| %>
      <%= location.label :location_name %>
      <%= location.text_field :name %>
    <% end %>
  </div>

Controller:

  def new
    @inventory_item = InventoryItem.new
    @inventory_item.build_location
  end

  def inventory_item_params
    params.require(:inventory_item).permit(:location_id, location_attributes:[:name])
  end

My problem is that I want that if the Location exists the new InventoryItem is associated with it. I don't now how to rebuild the association between InventoryItem and Location in case of Location with the name exists. The: @inventory_item.build_location in the controller is allways creating a new Location .

Thanks in advance

The accepts_nested_attributes_for :location adds a method to your InventoryItem model: location_attributes= .

You have a special constraint on this method, so you need to override it in inventory_item.rb, something like this:

#inventory_item.rb
def location_attributes=(attrs)
  begin
    self.location_id = Location.find_by!(name: attrs[:name])
  rescue ActiveRecord::RecordNotFound
    super
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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