Association many-to-many

John

My project has two entities Projects and Words. So a Project has many Wordsand a Word can be used in multiple Projects.

The Words table should only contain unique words, so that means if a project will add, a word which is already in the Words table, in the join table will be added the word_id against the project_id. Or if the word does not exist it should be added in the table in the association should be added into the join table.

So far I am able to add into tables, a project name which is stored into Projects table and a keyword name which is added into the Keyword table.

I am not convinced if my approach in solving this problem is good, also I don't know how to deal with the has_and_belongs_to_many(I don't thing that I need a has_many through association, because I don't do anything with the model at this point).

PinnyM

Firstly, you should absolutely use has_many_through over has_and_belong_to_many where possible. You can use find_or_create_by to ensure you only create keywords where not already found:

class Project < ActiveRecord::Base
  has_many :project_keywords
  has_many :keywords, :through => :project_keywords

  def add_keyword(name)
    keywords << Keyword.find_or_create_by(name: name)
  end
end

class Keyword < ActiveRecord::Base
  has_many :project_keywords
  has_many :projects, :through => :project_keywords

  validates :name, presence: true, uniqueness: true
end

class ProjectKeyword < ActiveRecord::Base
  belongs_to :project
  belongs_to :keyword
end

Now you can easily add keywords using the helper method add_keyword:

project = Project.create(name: 'My Project')
project.add_keyword('foo')

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related