0
当我使用以下命令:为什么这个连接表总是在执行posts_tags?
class CreateJoinTableTagsPosts < ActiveRecord::Migration
def change
create_join_table :tags, :posts do |t|
t.index [:tag_id, :post_id]
end
end
end
或以下:
class CreateJoinTableTagsPosts < ActiveRecord::Migration
def change
create_join_table :posts, :tags do |t|
t.index [:post_id, :tag_id]
end
end
end
我总是得到一个表,是posts_tags
,因此辅助方法在岗位模型:
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
实际上不工作。正如你所看到的assign_tag
方法不会实际工作,被这样做的测试:因为关系标签不存在
it "should create a page for a post" do
@post.assign_tag = 'Sample Tag'
end
失败。我相信这可以通过创建tags_posts
而不是它始终创建的合适连接表来解决posts_tags
想法?