New model insert overwriting others

2019-08-31 03:05发布

问题:

I have a rails application where I have two models called Column and Row:

Column:

has_many :rows

accepts_nested_attributes_for :rows, :reject_if => lambda { |b| b[:data].blank? }

Row:

belongs_to :column

And the form:

<%= form_for [@table, @row] do |f| %>

   <% @columns.each do |column| %>
       <%= f.label :data %><br>
       <%= f.text_area :data %>
   <% end %>

   <%= f.submit %>
<% end %>

and my create action in the controller:

@row = Row.new(row_params)

if @row.save
  redirect_to table_rows_path, notice: 'row was successfully created.' 
else
 render action: 'new'
end

and my new action:

@columns = Column.where(:table_id => @table.id)
@row = Row.new(id: @table.id)

So I have two problems. The first is if I have say two columns, so there will be two textfields on the new row page, and I enter "Test" in the first text field and "Another Test" in the second. The only thing that is getting saved is the second. The first one saves "Another Test" instead of "Test".

Also, how can I get the row (which belongs to a column) to save a column_id inside each row?

Thanks for all help!

回答1:

You are setting the new Row's id to the @table.id. Take that out; you never need to create a new .id. Then use column_id: params[:column_id] to link them up.