小编Ili*_*dev的帖子

在rails多态关联中查找父级

我正致力于实现多态注释(这些注释可以应用于网站上的任何用户内容,并不仅限于Article实例.在创建注释时,我需要确定commentable它属于哪个.我发现的大部分文字关于这个问题建议我使用find_commentable下面代码中指定的模式,但这种方法并没有让我觉得非常优雅 - 似乎应该有一种直接的方式来明确指定commentable正在创建的新注释,而不需要遍历该params集,并且没有字符串匹配,有没有更好的办法?

换句话说,是否有更好的方法在→ 关联的上下文中commentablecomment控制器访问对象?它仍然可以使用我们还没有一个对象可以使用的方法吗?commentablecommentcreate@comment

我的模型设置如下:

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

class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable, dependent: :destroy
end

class CommentsController < ApplicationController 
  def create
    @commentable = find_commentable  
    @comment = @commentable.comments.build(comment_params)

    if @comment.save
      redirect_to :back
    else  
      render :action => 'new'
    end  
  end

  def index
    @commentable = find_commentable
    @comments = @commentable.comments
  end

  private
    def …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails ruby-on-rails-4

4
推荐指数
2
解决办法
3339
查看次数