博客

问题描述 投票:0回答:2
发布

一个博客可以有多个帖子,而一个帖子属于一个博客。我正在使用以下命令:

    rails generate model Blog /* properties... */ post:has_many rails generate model Post /* properties... */ blog:belongs_to
  • 但是它根本不起作用(阅读:迁移和模型文件不是通过关联生成的)。也许我做错了。我应该仅在创建所有模型之后创建关联吗?
  • 此外,是否需要在两个模型中或仅在其中一个模型中声明关系?

    谢谢。

    这是我第一次使用Rails,我没有找到确切的方法来生成具有关联的新模型(和迁移)。例如,我有两个实体:博客帖子一个博客可以有很多帖子,...
ruby-on-rails activerecord orm associations
2个回答
0
投票
为此,您只需使用一个简单的:

rails generate model Blog /* properties... */

然后在模型中手动添加has_many :posts:)

0
投票
它还将关联添加到模型中:

# rails generate model Post blog:belongs_to class CreatePosts < ActiveRecord::Migration[5.0] def change create_table :posts do |t| t.belongs_to :blog, foreign_key: true t.timestamps end end end

为什么class Post < ApplicationRecord
  belongs_to :blog
end
不能使用相同的功能?

模型生成器的参数是模型的属性。 has_many是由数据库列支持的实际属性。blog_id不是属性。这是一个元编程方法,它向您的Blog实例添加了has_many方法。您需要将其手动添加到模型中。

如果运行posts,Rails实际上将使用这些属性创建迁移:

rails g model Blog posts:has_many foo:bar

Rails不键入检查参数。当然,迁移实际上不会运行:

class CreateBlogs < ActiveRecord::Migration[5.0] def change create_table :blogs do |t| t.has_many :posts t.bar :foo t.timestamps end end end

© www.soinside.com 2019 - 2024. All rights reserved.