Reputation: 1945
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
Upvotes: 0
Views: 224
Reputation: 6156
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
Upvotes: 1