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?

0


a source to share


3 answers


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

      

+4


a source


You need a lot of many relationships between these two objects.

  • The question can be studied by many people.
  • A person can study several questions.


Rails uses a helper has_and_belongs_to_many

for this. You will find more on this in the documentation and many blog posts!

has_and_belongs_to_many helper

+2


a source


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

0


a source







All Articles