0

I have a situation where Project can have many Tags (and vice versa), so I have set up a has_and_belongs_to_many relationship between the two.

My question is this: I need a project to have the ability to carry a single current tag.

Option 1

Can I add a tag_id to my Project table? How do I set up the relationship correctly, given there is already a `projects_tags' model?

Option 2

I'd imagine it isn't effective to have the projects_tags model carry a boolean current field, because it would require additional queries in practice for me to find the right relationship. I just throw it out there as an alternative I've considered.

sscirrus
  • 55,407
  • 41
  • 135
  • 228

1 Answers1

0

You could use something like this:

class Project < ActiveRecord::Base
  belongs_to :current_tag, :class_name => Tag
end

And then have current_tag_id in your projects table.

You can't add current to projects_tags because it's not technically a model: it's only a join table. You'd have to incorporate another model and use has_many :through to do it that way.

dnch
  • 9,565
  • 2
  • 38
  • 41
  • Dan, does that mean I can have both HABTM and belongs_to relationships between Project and Tag? – sscirrus Feb 17 '11 at 06:09
  • Of course! You just need to make sure that they're not the same name, which is why I used `current_tag` rather than just `tag` in my example above. – dnch Feb 17 '11 at 06:11
  • Question - if there are two relationships and I then call `Tag.projects.where...`, how can I specify which relationship to use? – sscirrus Feb 17 '11 at 07:11
  • You'd need to make sure that the relationship definition in `Tag` that corresponds to `Project.current_tag` is named something else, perhaps `current_projects` – dnch Feb 17 '11 at 11:22