0

I am having using rails 3 and have an HABTM(has_and_belongs_to_many) between users <-> emails Also user have roles defined for users as subs, pubs which have a Model that references to itself for mapping.

I want to send some emails to trash/spam/etc for one single user. How can I achieve, as if I delete one email it'll be removed for every user having HABTM. I just want to show that email as trashed/spam etc. I have a wild thought of overriding the HABTM table by setting spam/trash flags/columns in the table, so that when a user marks spam/trash to an email. He'll be able to work Is there any way/convention to do that.

Nishutosh Sharma
  • 1,926
  • 2
  • 24
  • 39

1 Answers1

1

I reckon you can get away with setting up your associations as shown below. Note the dependent: :destroy. When you delete your user ActiveRecord will cause the call dependent: :destroy on the model and delete the associated model with it.

class User < ActiveRecord::Base 
  has_many :emails, through: :user_emails
  has_many :emails, dependent: destroy 
end 

class UserEmail < ActiveRecord::Base
  belongs_to :user 
  belongs_to :email 
end 


class Email < ActiveRecord::Base 
  has_many :users, :through: :user_emails 
  has_many :user_emails, :dependent: :destroy 
end 

You can have a look under Polymorphic Associations. Hopefully this helps

Update Querying has_many Association

 @UserEmail = UserEmail.find(:all,
    :joins => :user, :email,
    :conditions => ["email.email_trashed = ? ", true] 
    )

Not 100% certain that this will work but I reckon it is along them lines.

Deej
  • 5,334
  • 12
  • 44
  • 68
  • that means, I can create a model for that HABTM and use that ..?? – Nishutosh Sharma Jul 19 '13 at 04:28
  • 1
    @NishutoshSharma yeah you should be able to. When designing your application you should consider that it is not very good to have many-to-many relationships. Which is why we can resolve this form of cardinality by creating a resolving table. In which case this is `UserEmail` – Deej Jul 19 '13 at 08:00
  • I have made a slight change please check and confirm that purpose will be served.. so that I can mark this answer right – Nishutosh Sharma Jul 19 '13 at 12:54
  • I have seen your edit, it sounds pretty reasonable as in if you set the fields, `spam` and `trash` to boolean fields, so that determine whether the fields have been marked will deter what happens to the email. – Deej Jul 19 '13 at 14:41
  • if I take an column, :trashed in :emails_users table then how will I find emails that are trashed => true.. I am finding it difficult to search through the columns of EmailsUser model. Do we have any standard way of querying this has_many through table ?? – Nishutosh Sharma Jul 22 '13 at 14:32
  • @NishutoshSharma see my update hopefully it will shed some light – Deej Jul 24 '13 at 11:18