Suppose I have posts, which have many categories through categorizations. Suppose that I add a boolean column primary to categorizations in order to determine the primary category of a post. But now I’m stuck dealing with the join model, when what I’d really like to do is something like this:
post = Post.first
primary_cat = post.categories.where(:primary => true)
post.categories.first.primary = true
post.save # would actually update the categorization, setting primary = true
There are all sorts of examples I could give you to show why this would be useful, but essentially I want to be able to interact with a model as though it is somehow merged with its join model. Being able to say “What’s the primary category?” or “OK this category will be the primary one” without ever touching the join model is the intuitive for me the think of this.
Is this even possible with Rails? Has anyone seen a effort to do this sort of thing before?
I like quest’s solution except that setting it should just be
post.primary_category=and should take a category object. Just setup ahas_one :primary_categoryon post and you’re golden.