Ruby on Rails - 如何在泛型方法中添加n:m关联

时间:2016-08-12 07:29:40

标签: ruby-on-rails ruby generics

假设两个模型属于has_and_belong_to_many关系,例如司机&汽车 在Rails中,您可以使用

添加新关系
driver.cars << car 

现在,如何使这一行变得通用? 在控制器中,方法调用移交一个驱动程序实例,一个字符串表示关联类&#39; cars&#39;和一系列汽车ID要添加。

add_association(@driver, 'car', [car_ids])

方法看起来像这样。

  def add_association(object, association_class_name, ids)
    model = association_class_name.constantize
    associations = association_class_name.pluralize

    ids.each do |incoming_id|
      association = model.find_by_id(incoming_id)
      if association.nil?
        return false
      else
        object.associations << association # throws NoMethodError: undefined method `associations' for #<Driver:0x...
      end
    end
  end

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

用户 public_send 方法如下:

def add_association(object, association_class_name, ids)
  model = association_class_name.constantize
  associations = association_class_name.underscore.pluralize

  ids.each do |incoming_id|
    association = model.find_by_id(incoming_id)
    if association.nil?
      return false
    else
      object.public_send associations << association 
    end
  end
end

参考:public_send

如果它不起作用,请告诉我。