为多个对象分配当前用户?

时间:2011-12-11 01:52:34

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

在下面的代码中,我想将当前用户分配给创建的产品。

ProductsController.rb

def new
  @products = Array.new(2) { Product.new }   
end

def create_multiple
  params[:product][:user_id] = current_user.id
  Product.transaction do
    begin
      @products = Product.create!(params[:products].map {|_k, up| up.merge params[:product]})
      redirect_to :back, :notice => "Success!"
    rescue ActiveRecord::Rollback
      redirect_to :back, :notice => "An error occured, please try again."
    end
  end
end

new.html.erb

<%= form_tag create_multiple_products_path, :method => :post do %>

  <%= date_select("product", "purchase_date")  %>

  <% @products.each_with_index do |product, index| %>
     <%= fields_for "products[#{index}]", product do |up| %>
        <%= render "fields", :f => up %>
     <% end %>
  <% end %>

  <%= submit_tag "Done" %>
<% end %>

未分配USER ID(当前用户)。关于如何分配它的任何想法?

2 个答案:

答案 0 :(得分:1)

def create_multiple
  @products = params[:products].values.collect do |up|
    Product.new(up.merge(params[:product]).merge(:user_id => current_user.id))
  end

  # should run in a transaction, don't half save!
  Product.transaction do
    @valid = @products.all?(&:save)
  end

  if @valid
    redirect_to :back, :notice => "Success!"
  else
    redirect_to :back, :notice => "An error occured, please try again."
  end
end

答案 1 :(得分:1)

你可以通过记住两个事实来消除很多逻辑:create将使用一个Hashes数组来创建多个对象,并且如果有任何验证,它的bang-method对应create!将抛出异常失败。

def create_multiple
  # like clyfe said, do this in a transaction
  Product.transaction do
    begin
      @products = current_user.products.create!(
        # Hash#map returns an Array, so no need to use Hash#values
        params[:products].map { |_k, up| up.merge params[:product] }
      )

      # if create! is successful...
      redirect_to :back, :notice => "Success!"

    # if it's not successful it'll throw this exception, which we can rescue
    rescue ActiveRecord::Rollback
      redirect_to :back, :notice => "An error occured, please try again."
    end
  end
end

处理create!问题的一种方法是删除before_filter中的任何“空白”条目,例如:

before_filter :toss_blank_products

def toss_blank_products
  params[:products].reject! do |prod|
    # this logic may need to be more complex depending on the meaning of "blank"
    # for your model/form
    prod.values.all? &:blank
  end
end