Question

When I use the following:

class CreateJoinTableTagsPosts < ActiveRecord::Migration
  def change
    create_join_table :tags, :posts do |t|
        t.index [:tag_id, :post_id]
    end
  end
end

or the following:

class CreateJoinTableTagsPosts < ActiveRecord::Migration
  def change
    create_join_table :posts, :tags do |t|
        t.index [:post_id, :tag_id]
    end
  end
end

I always get a table that is posts_tags and as a result helper methods in the posts model:

class Post < ActiveRecord::Base
  belongs_to :blogs

  has_and_belongs_to_many :tags, join_table: 'tags_posts'
  has_and_belongs_to_many :categories, join_table: 'categories_posts'
  has_many :comments

  validates :title, presence: true

  def has_tag?(tag_name)
    tag == tag_name
  end

  def assign_tag=(tag_name)
      tag = Tag.find_by(name: tag_name) || Tag.create(name: tag_name)
      self.tag = [tag] if tag
  end

end

Don't actually work. As you can see the assign_tag method wont actually work, tests that are done as such:

it "should create a page for a post" do
  @post.assign_tag = 'Sample Tag'
end

fails because relation tags doesn't exist. I believe this can be solved by creating the appropriate join table of tags_posts instead of the one it always creates posts_tags

ideas?

Was it helpful?

Solution

create_join_table uses the lexical order of the arguments to name the table.

You can override this using a table_name option:

create_join_table :posts, :tags, table_name: 'tags_posts' do |t|
    t.index [:post_id, :tag_id]
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top