我有一个表单,需要创建两个对象:sale和organization。这种情况发生在sales_controller内部。
为了简洁起见,模型及其属性是:
sale
amount (integer)
organization_id (uuid)
organization
name (string)
sale belongs_to organization
organization has_many sales

这就是sales new应该看起来的样子。它有一个用于sales的输入,哪个用户将输入,它也有一个组织名称的输入,哪个用户将输入。提交后,用户将创建一个新的销售(另外还创建了一个与该销售相关联的新组织)。
我正在试图找出create方法在sales_controller中的最佳实践是什么。
def create
@sale = Sale.new(sale_params) #assume sale_params permits organization_id and amount
@organization = Organization.create(params[:name])
#@sale.organization_id = @organization.id
if @sale.save
render json: @sale
else
render json: sale, status: :unprocessable_entity
end
end@organization = Organization.create(...)感觉不对。是否有一种方法来完成多个对象提交"Rails"-way?
发布于 2017-04-19 20:27:57
由于您可能已经在以前的销售中创建了一个组织,所以您可以使用:
@organization = Organization.find_or_create_by(name: params[:name])
然后通过关联sale.organization_id来继续。您还需要在Organization.name上有一个唯一性约束。
https://stackoverflow.com/questions/43505264
复制相似问题