【问题标题】:polymorphic association belongs to User多态关联属于用户
【发布时间】:2015-02-24 19:23:46
【问题描述】:

我有一个 cmets 模型,它是一个涉及状态和照片的多态关联。如何创建此多态关联以也属于用户,以便当用户在状态或照片下创建评论时,它也会收到 current_user id?

这就是我现在所拥有的-

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

class User < ActiveRecord::Base
  has_many :comments
end

class Status < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Photo < ActiveRecord::Base
  has_many :comments, as: :commentable
end

重申一下,我怎样才能以用户的身份创建评论,同时将其置于状态或照片下?它需要 user_id。

这就是我遇到麻烦的地方- 我应该如何设置?

def create 
    @comment = @commentable.comments.new(comments_params) 
    if @comment.save
      redirect_to @commentable, notice: "Comment created"
    else
      render :new
    end
  end

【问题讨论】:

    标签: ruby-on-rails model-view-controller rails-activerecord polymorphic-associations


    【解决方案1】:

    试试这个

    class Comment < ActiveRecord::Base
      belongs_to :likable, :polymorphic => true
      belongs_to :commentable, :polymorphic => true
      belongs_to: user
    
    class User < ActiveRecord::Base
      has_many :statuses, :as => :likable
      has_many :photos, :as => :commentable 
      has_many :comments   
    
    
    class Status < ActiveRecord::Base
      has_many :comments, :as => :likable, :dependent => :destroy  
    
    
    class Photos < ActiveRecord::Base
      has_many :comments, :as => :commentable, :dependent => :destroy  
    

    【讨论】:

    • 你能解释一下吗?
    • 如果你说@comment.likable 应该返回状态,@comment.commentable 应该返回照片,@user.photos@user.statuses 应该为该用户提供photosstatuses
    • 你应该可以创建@comment = @status.comments.new(comments_params)@comment = @photo.comments.new(comments_params)
    【解决方案2】:

    这有点 hacky,但我找到了解决方法。所以在我的 CommentsController 中我这样做了:

    def create 
        new_params = comments_params
        new_params[:user_id] = current_user.id
        @comment = @commentable.comments.build(new_params)
    
        if @comment.save
          redirect_to @commentable, notice: "Comment created"
        else
          render :new
        end
      end
    

    放置了我需要的 user_id。

    【讨论】:

    • 这个很老了,我已经回答过了。你可以从这个 www.xyzpub.com/en/ruby-on-rails/3.2/activerecord_polymorphic.html 中很好地理解
    猜你喜欢
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多