【发布时间】:2015-11-24 02:22:04
【问题描述】:
我正在开发一个博客 Rails 应用程序。我想让每个帖子都有很多标签,并且能够显示属于给定标签的所有帖子。我已经按照Rails Guide 设置了has_and_belongs_to_many 关系,我还尝试了this tutorial。
在模型设置好后,我两次进入 Rails 控制台检查表格的格式是否正确。我打电话给Post.new 和Tag.new。每个都在表中给我一个新的实例/条目,但都没有显示用于引用另一个的列。不应该有一个吗?如果没有,我应该如何构建我的种子数据?
到目前为止,我只处理了belongs_to 和has_many 关系。如果有人在has_and_belongs_to_many 上有一个更好的解释/教程的链接,我也将不胜感激,我的搜索并没有很清楚。
这是我的代码:
post.rb:
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
belongs_to :categories
end
tag.rb:
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
longnumber_create_posts.rb:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :name
t.string :content
t.datetime :pub_time
t.integer :category_id
t.timestamps null: false
end
end
end
lognumber_create_tags.rb:
class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :name
t.timestamps null: false
end
end
end
longnumber_create_posts_and_tags.rb:
class CreatePostsAndTags < ActiveRecord::Migration
def change
create_table :posts_tags, id: false do |t|
t.belongs_to :post, index: true
t.belongs_to :tag, index: true
end
end
end
schema.rb:
ActiveRecord::Schema.define(version: 20151123235501) do
create_table "posts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts_tags", id: false, force: :cascade do |t|
t.integer "post_id"
t.integer "tag_id"
end
add_index "posts_tags", ["post_id"], name: "index_posts_tags_on_post_id"
add_index "posts_tags", ["tag_id"], name: "index_posts_tags_on_tag_id"
create_table "tags", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
【问题讨论】:
-
如果你能把你的数据库结构和你的模型贴在这里就好了。
标签: ruby-on-rails ruby has-and-belongs-to-many