如果在视图演示之前尚未创建连接表记录,则生成连接表

时间:2015-02-22 13:48:40

标签: ruby ruby-on-rails-3.2

产品模型需要通过嵌套表单更新其数据,并为其连接表提供各种数据

Product
  has_many :productunits, dependent: :destroy
  has_many :units, through: :productunits
Unit
  has_many :productunits, dependent: :destroy
  has_many :products, through: :productunits

调用@productunits = Productunit.where(['product_id = ?', params[:id]]).all时,仅显示现有的产品单元。如果在此期间创建了单位,则建议的列表不完整。 然而,编辑操作需要创建新的产品单元并使用各种初始数据(如果它们尚不存在),之前在视图中显示它们。

什么ruby语法可以实现这个结果?

更新 我已启用控制器执行以下操作

before_filter :set_product_units, :only => [:edit]
private
def set_product_tipounits
  @units = unit.where(['org_id = ?', session[:org_id]]).all
  @productunits = Productunit.order("id ASC").where(['product_id = ?', params[:id]]).all
  @units.each do |unit|
    @join_created = Productunit.where(['product_id = ? AND unit_id = ?', params[:id], unit.id]).first
    if @join_created.nil?
      @productunit = Productunit.new(:product_id => params[:id], :unit_id => unit.id, :auto_generate => false, :auto_price => false, :release_days => "30")
      @productunit.save      
    end
  end

问题解决了......

1 个答案:

答案 0 :(得分:1)

我很高兴你找到了解决方案,但是你的解决方案确实让你的控制器知道的更多信息需要知道" has_many_through"关系。

更抽象的解决方案可能是......

在UnitController的create方法

def create
...
if @unit.save
  Product.all.each{|p| p.units << @unit unless p.units.include? @unit}
  ...
  end
end

同样在ProductController中

def create
...
if @product.save
  Unit.all.each{|u| u.products << @product unless u.products.include? @product }
  ...
  end
end

EDIT 您也可以将此作为模型中的回调。

class Unit << ActiveRecord::Base
  after_save :add_to_products

  def add_to_products
    Product.all.each{|p| p.units << self unless p.units.include? self}
  end 
end