Ruby On Rails - One for Many
I am starting ROR, but here is what I am trying to achieve. I have two subjects that I want to connect: questions and people. Each question can have many people. That is, I want to create people and questions separately, and later they can be linked.
For example, I can create: Bill Clinton Barack Obama
I Can Ask Questions: Global Warming War on Terror
I want to be able to connect users of Bill Clinton and Barack Obama with BOTH questions. Can anyone point me to a tutorial that can show me how to do this?
I think it has_and_belongs_to_many
is being used less and less by the RoR community. While I still maintain, I think it is now more common to have an intermediate model (in your case something like PoliticianMatter
) to join your models Politician
and Matter
.
Then your table politician_matter
will have PK, a politician_id
and matter_id
.
Then you have
class PoliticanMatter < ActiveRecord::Base
belongs_to :politician
belongs_to :matter
end
The advantage of this approach is that if there ever should be future properties of politics -> matter relations (e.g. importance, date of last occurrence), you have a model that gives this - has_and_belongs_to_many
will not support adding these additional properties.
You can also access many relationships directly from the Politics and Matter models such as
class Politician < ActiveRecord::Base
has_many :politician_matters
has_many :matters, :through => :politician_matters
end
class Matter < ActiveRecord::Base
has_many :politician_matters
has_many :politicians, :through => :politician_matters
end
a source to share
class Politician < ActiveRecord::Base
has_and_belongs_to_many :tasks
end
class Task < ActiveRecord::Base
has_and_belongs_to_many :politicians
end
You need 3 tables:
politicians, tasks
and politicians_tasks
(with two columns politician_id
and task_id
, no primary key)
Hope this helps Seb
a source to share