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

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206

1 Answers1

1

For your first question, you want ObjectTypesAsso to be unique on :object_id and :type_id attributes

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

rails 3 validation on uniqueness on multiple attributes

For the second question, if I understood what you wan to do, you can ovewrite the list of types like this:

object.types = [Types.find(xx), Types.find(yy)]
Community
  • 1
  • 1
dyanisse
  • 114
  • 1
  • 8