0

I can't achieve what I want here, but I have the feeling it is possible in Rails.

I have two models and an association one.

class Object < ActiveRecord::Base

  attr_accessible :object_types_asso, :object_types_asso_attributes
  accepts_nested_attributes_for :object_types_asso, :allow_destroy => true


  has_many :types, :through => :object_types_asso
  has_many :object_types_asso

end

class Types < ActiveRecord::Base

  attr_accessible :object_types_asso, :object_types_asso_attributes
  accepts_nested_attributes_for :object_types_asso, :allow_destroy => true

  has_many :object, :through => :object_types_asso
  has_many :object_types_asso

end

class ObjectTypesAsso < ActiveRecord::Base
  attr_accessible :object_id, :type_id

  belongs_to :object
  belongs_to :types

end

I'd like to have an active record unicity constraint on ObjectTypesAsso so that I don't have two ObjectTypesAsso records with the same :object_id and :type_id and so that when one exists, it gets updated instead of creating a new one (or ignored if updating is not possible).

How could I achieve that?

The second part of the question is how could I manage the assos doing something like:

object.update_attributes({:object_types_asso_attributes => [{:types_id => xx}, {:types_id => yy}]})

and it creates asso with types_id=xx and types_id=yy if they don't exist, AND deletes types_id=zz if it existed since it is not in the list. The idea is to have a checkbox list that updates the associations wether it is checked or not.

Could I also do this?

Thanks

4

1 回答 1

1

对于您的第一个问题,您希望 ObjectTypesAsso 在 :object_id 和 :type_id 属性上是唯一的

validates :object_id, :uniqueness => {:scope => :type_id}

rails 3验证多个属性的唯一性

对于第二个问题,如果我了解您要做什么,您可以像这样覆盖类型列表:

object.types = [Types.find(xx), Types.find(yy)]
于 2013-10-12T01:01:43.713 回答