gpt4 book ai didi

ruby-on-rails - 为多个对象分配当前用户?

转载 作者:太空宇宙 更新时间:2023-11-03 16:08:42 25 4
gpt4 key购买 nike

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

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(当前用户)。关于如何分配它有什么想法吗?

最佳答案

你可以通过记住两个事实来消除这里的很多逻辑:create 将采用哈希数组来创建多个对象,而它的 bang 方法对应物 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

关于ruby-on-rails - 为多个对象分配当前用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8461372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com