I have looked at various answers to similar questions and haven't quite cracked it.
A wine
model is defined with has_one :register, :dependent => :destroy
and rightly or wrongly I have added accepts_nested_attributes_for :register
. A register
is defined with belongs_to :wine
.
The code within wines_controller.rb
for create
is:
def new
@wine = Wine.new
@register = Register.new
def create
@wine = Wine.new(wine_params)
@register = @wine.registers.build(register_params)
respond_to do |format|
if @wine.save
#success
else
format.json { render json: @wine.errors, status: :unprocessable_entity }
format.json { render json: @register.errors, status: :unprocessable_entity }
end
end
end
My form for creating a new wine
has the following code:
<%= simple_form_for @wine do |f| %>
# various working elements
<div class="field">
<% f.fields_for :register do |r| %>
<%= r.label :short_name %>
<%= r.text_field :short_name %>
<%= r.label :barcode %>
<%= r.text_field :barcode %>
<% end %>
</div>
When this form is called up no fields are created from the f.fields_for
command but this block is executed because I can add test buttons within it to prove it is accessed.
If I try to create a wine I get the following error message:
undefined method `registers' for #<Wine:0x007f1204375330> Did you mean? register register= register_id
I believe that using .build
is there to ensure data integrity: I don't want to create a wine
that does not have a corresponding register
. I have tried thinking about it nested attributes but that seems to be considered a bad plan by many. This current approach feels correct but I think I am missing some understanding of syntax at the very least.
At a later date it will be necessary to have other models linked to register
that will not be associated to wines. I was considering a similar approach but I am happy to be told to rethink!