Принятие вложенных атрибутов для родительской модели - PullRequest
3 голосов
/ 19 января 2012

При попытке принять вложенный атрибут для модели пользователя появляется следующая ошибка:

Couldn't find User with ID=1 for Sale with ID=

Продажа модели:

class Sale < ActiveRecord::Base

   belongs_to :user

   accepts_nested_attributes_for :user

end

Модель пользователя:

class User < ActiveRecord::Base
   has_many :sales
end

Просмотр шаблона:

<%= form_for @sale, :html => {:class => "stagedForm bigForm"} do |f| %>
    <% if @sale.errors.any? %>  
        <div id="errorExplanation">  
            <h2><%= pluralize(@sale.errors.count, "error") %> prohibited this user from being saved:</h2>  
            <ul>  
                <% @sale.errors.full_messages.each do |msg| %>  
                    <li><%= msg %></li>  
                <% end %>  
            </ul>  
        </div>  
    <% end %>

    <fieldset>
    <legend>When</legend>
    <div class="field">
        <%= f.label :start_time %>
        <%= f.datetime_select :start_time, :minute_step => 10, :default => Time.now+1.week, :order => [:day, :month, :year] %>
      </div>
      <div class="field">
        <%= f.label :end_time  %>
        <%= f.datetime_select :end_time, :default => Time.now+( 1.week + 2.hours), :minute_step => 10, :order => [:day, :month, :year] %>
      </div>
    </fieldset> 

    <fieldset>
        <legend>Payment</legend>
        <%= f.fields_for :user do |u| %>
            <%= u.hidden_field :stripe_card_token %>
        <% end %>

    </fieldset>

    <div style="clear:both;"></div>
  <div class="actions">
    <%= f.submit "create", :id => "saveForm" %>
  </div>
<% end %>

Контроллер продаж:

def new
    user = User.find(current_user.id)
    @sale = user.sales.build
    logger.debug "user locations #{user.locations}"
    @locations = user.locations
    1.times { @sale.items.build; @sale.build_location; }
  end


def create
    @sale = Sale.new(params[:sale])
    @sale.user_id = current_user.id

    logger.debug "Sale object!!!  #{@sale.inspect}"
    respond_to do |format|
      if @sale.save
        format.html { redirect_to @sale, notice: 'Sale was successfully created.' }
        format.json { render json: @sale, status: :created, location: @sale }
      else
        format.html { render action: "new" }
        format.json { render json: @sale.errors, status: :unprocessable_entity }
      end
    end
  end

1 Ответ

1 голос
/ 19 января 2012

Вложенные атрибуты позволяют сохранять атрибуты в связанных записях через родительский элемент.Таким образом, вы должны иметь acceptpts_nested_attributes_for: sales в модели пользователя.

И вложенные атрибуты приходят на помощь, когда вы пытаетесь обновить модель пользователя продажами как дочерние записи.

Вы должны использовать hidden_field_tag ​​для передачи user_idв представлении (выше, связанном с продажей) или как продажа принадлежит пользователю, вы можете использовать тег выбора, чтобы выбрать пользователя.

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

...