0

在 Rails 控制台中执行 User.first 和 Post.first 工作正常。Post.first.user 工作正常,但 User.first.posts 给了我一个未定义的方法错误

型号:

class User < ActiveRecord::Base
    attr_accessible :role :user_email, :user_name

    has_many :posts
end

class Post < ActiveRecord::Base
    attr_accessible :content, :status, :title, :user_id

    belongs_to :user
    has_many :comments
end

当我创建一个新项目时,一切正常,但在这种情况下,我做了一些不同的事情。我将现有数据库(sqlite)从另一个 Web 应用程序(非 Rails)改编为 Rails。我所做的是重命名列以适应 Rails 约定,以前我使用用户名作为唯一键并使用它来链接到帖子所有者我将列名更改为 user_id 并将所有值更新为相关的用户 ID。我也将列类型和值更改为 int 值。

评论也是如此: Comment.first.post 有效,但 Post.commments 给出了未定义的方法错误。

执行 User.joins(:post(s)) 时,我收到错误“未找到名为‘posts’的关联”,但 Post.joins(:user) 工作正常。

编辑:对我感到羞耻 - 我遗漏了我认为不相关的相关信息。

无论如何 - 我有一个名为角色的列,所以用户模型有 attr_accessible :role --- 一次 > 我删除了一切都按预期工作。

但是,我不明白为什么这会有所作为。这:> https://github.com/ryanb/cancan/wiki/Role-Based-Authorization用户模型具有 :role 并且我 > 会假设任何基于用户的应用程序都具有 has_many 依赖项,因此会像我的那样失败。

...还是我还缺少其他东西?

4

0 回答 0