代码之家  ›  专栏  ›  技术社区  ›  JP Silvashy Gautam Rege

Rails,对多态关联的混淆

  •  1
  • JP Silvashy Gautam Rege  · 技术社区  · 14 年前

    我在这里有点困惑,似乎无法在网上找到合适的资源或信息。

    class Comment < ActiveRecord::Base
      belongs_to :commentable, :polymorphic => true
      belongs_to :user
    end
    

    因此,注释还包含列 commentable_type commentable_id ,

    class Thing < ActiveRecord::Base
      has_many :comments, :as => :commentable
    end
    

    窗体和所有内容都呈现并工作良好,记录保存,但 可注释类型 可注释的\u id 专栏,我不明白我在这里遗漏了什么。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Community CDub    7 年前

    这个问题会帮助你四处走动 polymorphic associations

    这就是我的回答,也建议你也这样做。 由于您已经在模型中创建了多态关联,因此在视图中不必再担心这个问题。你只需要在你的评论控制器中这样做。

    @movie = Movie.find(id) # Find the movie with which you want to associate the comment
    @comment = @movie.comments.create(:text => "This is a comment") # you can also use build
    # instead of create like @comment = @movie.comments.build(:text => "This is a comment")
    # and then @comment.save
    # The above line will build your new comment through the movie which you will be having in
    # @movie.
    # Also this line will automatically save fill the commentable_id as the id of movie and 
    # the commentable_type as Movie.
    
        2
  •  1
  •   Coderama    14 年前

    c = Comment.create
    t = Thing.create
    c.commentable = t
    c.save!