简体   繁体   中英

Rails3 update existing record, create new simultaneously

Quote model has a number of variables. A quote can be added to a Cart, as a LineItem. Quote has_many :line_items,

LineItem 
  belongs_to :quote
  accepts_nested_attributes_for :quote

The idea is that if a Quote is added to the cart, its status changes (:final => true) quote_controller in its show action instantiates

 @line_item = LineItem.new

The Quote's show view includes a form which needs to do two things simultaneously:

  1. create the line_item. This is generated by <%= f.hidden_field :quote, :value => @quote.id %>
  2. update the quote.

The second element is the issue

<%= form_for(@line_item) do |f| %>
 [...]
  <%= fields_for @line_item.quote do |quote_fields| %>
    <%= quote_fields.hidden_field :final, :value => true %>
  <% end %>
<% end %>

This returns the error undefined method 'model_name' for NilClass:Class . Odd though, the context is already that model.

The question was a garden path. The mistake is

A quote can be added to a Cart, as a LineItem.

No need for the LineItem. Quote can belong to a Cart. The assignment of cart_id does the trick. Then the show view includes a form to edit that same record

    <%= form_for(@quote) do |f| %>
      <%= f.hidden_field :cart_id, :value => @cart.id %>

The cart then contains all its quotes and whatever it needs.

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