接受父模型的嵌套属性

时间:2012-01-18 22:09:31

标签: ruby-on-rails ruby ruby-on-rails-3 rails-activerecord

尝试接受用户模型的嵌套属性时,我收到以下错误:

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 个答案:

答案 0 :(得分:1)

嵌套属性允许您通过父级保存关联记录的属性。所以你应该在用户模型中拥有accepts_nested_attributes_for:sales。

当您尝试使用sales作为子记录更新用户模型时,嵌套属性就会被拯救。

您应该使用hidden_​​field_tag从视图中传递user_id(上面与Sale相关联)或者当销售属于User时,您可以使用select标签来选择用户。

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