【问题标题】:Can't add multitenancy attribute to nested model无法将多租户属性添加到嵌套模型
【发布时间】:2015-04-05 03:21:20
【问题描述】:

我正在尝试使用 Ruby on Rails 4.2.1 和 PostgreSQL 创建一个应用程序。

我有以下型号。

class Builder < ActiveModel
  has_many :bills
  has_many :bills_partials
end

class Bill < ActiveModel
  belongs_to :builder
  has_many :bills_partials

  accepts_nested_attributes_for :bills_partial, :reject_if => :all_blank, :allow_destroy => true
end

class BillPartial < ActiveModel
  belongs_to :builder
  belongs_to :bills
end

以及以下操作

def new
  bill.bills_partials.build
end

def create
  @bill = Bill.scoped_to(current_builder).new(bill_partial_params)
  if @bill.save
    redirect_to bills_path, flash: { success: t('flash.generic.female.created', model: Bill.model_name.human) }
  else
    render :new
  end
end

private
  def bill
    @bill ||= Bill.scoped_to(current_builder).find_by(id: uuid_or_nil(params[:id])) || Bill.scoped_to(current_builder).new
  end
  helper_method :bill

  def bill_params
    params
      .require(:bill)
      .permit(:description,
              :value,
              :date,
              bills_partials_attributes: [:id,
                                          :due_date,
                                          :valor,
                                          :_destroy])

  end

参数的输出是:

{
  "description"=>"some desc",
  "value"=>"123",
  "date"=>"10/10/2010",
  "bills_partials_attributes" =>
  {
    "0" =>
    {
      "due_date"=>"14/03/2003",
      "value"=>"123"
    },
    "1" =>
    {
      "due_date"=>"14/03/2003",
      "value"=>"123"
    }
  }
}

问题是,我必须为每个模型添加current_builder.id,例如BillBillPartial。在BillPartial 模型上将current_builder.id 添加到builder_id 的最佳方法是什么?

【问题讨论】:

    标签: ruby-on-rails simple-form nested-attributes


    【解决方案1】:

    嗯,找东西后,我通过定义解决了这个问题

    before_create do
      self.builder_id = bill.try(:builder_id)
    end
    

    在 BillPartial 模型上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多