【问题标题】:Rails associations of user/post/comment用户/帖子/评论的Rails关联
【发布时间】:2011-02-07 06:58:00
【问题描述】:

我正在尝试创建一个类似于博客的应用程序,具有 3 个模型:用户、帖子和评论。正如预期的那样,评论既属于用户,也属于帖子。

我使用了以下关联:

用户.rb

has_many :comments
has_many :posts

Post.rb

has_many :comments
belongs_to :user

评论.rb

belongs_to :user
belongs_to :post

我尝试使用以下方法创建 cmets: @user.cmets.create

但是,这会将评论与用户相关联,而不是与帖子相关联。我希望评论与用户和帖子相关联。有没有办法这样做?还是我使用了错误的关联?

我认为手动设置 user_id 或 post_id 可能是一种不好的做法,因此这两个 id 都不在 attr_accessible 中。我不确定它是否正确。

谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您不需要专门设置post_id。试试@user.comments.create(:post => @post)

    【讨论】:

    • 这听起来像你想要的 - 多态答案是针对错误的问题......如果你希望能够通过创建时的哈希设置这些属性,但保护它们不被修改正在更新的用户,请查看 attr_readonly:link
    • 当我尝试:@user.comments.create(:content => "hi", :post => @post),我得到:#<Comment id: nil, user_id: 1, post_id: nil, content: "hi", created_at: nil, updated_at: nil>@post#<Post id: 4, title: "fooTitle", content: "fooContent", user_id: 1, created_at: "2011-02-07 20:13:43", updated_at: "2011-02-07 20:13:43"。似乎评论后关联仍然缺失。我不确定出了什么问题。谢谢!
    • 奇数。我创建了一个测试应用程序,其中包含一组用户、帖子、评论类。通过控制台user = User.create; post = Post.new; user.comments.create(:post => post) 产生#<Comment id: 1, user_id: 1, post_id: 1, created_at: "2011-02-08 09:46:53", updated_at: "2011-02-08 09:46:53">。你能检查一下你的数据库中的评论是什么吗?需要重新加载吗?你能准确地发布你所做的事情吗?
    • 我检查了日志,上面写着WARNING: Can't mass-assign protected attributes: post。我想这是因为我只将content 放在`attr_accessible:content. Do I have to put post_id` 那里进行关联?有人告诉我这可能不是一个好习惯。谢谢!
    • 我尝试将 post_id 设置为 attr_accessible 并手动将其设置为与当前帖子相关联。它是这样工作的。
    【解决方案2】:

    如果评论需要关联多个模型,我们称之为polymorphic association。您可以查看has_many_polymorphs 插件。我假设您使用的是 rails 3,您可以尝试以下操作:

    您可以像这样在lib/commentable.rb 文件夹中定义模块:

    module Commentable
        def self.included(base)
            base.class_eval do
                has_many :comments, :as => commentable
            end
        end
    end
    

    在 Comment 模型中你应该说它是多态的:

    belongs_to :commentable, :polymorphic => true
    

    在 Post 和 User 模型中,您可以添加以下内容:

    has_many :comments, :as => :commentable, :dependent => :delete_all
    

    因为在 Rails 3 中 lib 文件夹默认不会加载,所以你应该让 Rails 将它加载到你的 application.rb 中:

    config.autoload_paths += %W(#{config.root}/lib)
    

    现在,Comment 是多态的,任何其他模型都可以与之关联。应该这样做。

    【讨论】:

    • 我认为这意味着评论只能与UserPost 之一相关联,这听起来不像OP的意图。
    猜你喜欢
    • 2022-11-09
    • 2013-06-08
    • 2023-04-10
    • 1970-01-01
    • 2016-05-27
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多