简体   繁体   English

多态模型用户关联

[英]Polymorphic model user association

Rails 3.2. Rails 3.2。 I am using the following code to associate user_id to the record: 我使用以下代码将user_id与记录关联:

  # review.rb
  class Review < ActiveRecord::Base
    belongs_to :reviewable, :polymorphic => true, :counter_cache => true
  end

  # reviews_controller.rb
  def create
    @review = @reviewable.reviews.new(params[:review])
    @review.user_id = current_user.id
    if @review.save
      flash[:success] = 'Thanks for adding your review.'
      redirect_to @reviewable
    else
      flash[:error] = 'Error adding review,  please try again.'
      redirect_to @reviewable
    end
  end

I want to find a way to use this, but it keeps saying that the current_user is not defined, but I could find the current_user object: 我想找到一种方法来使用它,但它一直说没有定义current_user ,但我可以找到current_user对象:

  def create
    @review = @reviewable.current_user.reviews.create(params[:review]
    if @review.save
      flash[:success] = 'Thanks for adding your review.'
      redirect_to @reviewable
    else
      flash[:error] = 'Error adding review,  please try again.'
      redirect_to @reviewable
    end
  end

If you can post your code to what the @reviewable object is, it might help to give a more specific answer. 如果您可以将代码发布到@reviewable对象的内容,则可能有助于提供更具体的答案。 But if you want a one liner, you can do something like this: 但如果你想要一个衬垫,你可以这样做:

@review = @reviewable.reviews.build(params[:review].merge({:user_id => current_user.id})

But personally, i think your original looks better as it's easier to read. 但就个人而言,我认为你的原版看起来更好,因为它更容易阅读。

As an additional note, your second example also calls create and save. 作为补充说明,您的第二个示例也称为创建和保存。 You don't need to call both, as create saves the object when accepting a hash of parameters. 您不需要同时调用它们,因为create在接受参数哈希时会保存对象。 Save is nice to use if you want to initialize an object, modify it in some way, then save it later. 如果要初始化对象,以某种方式修改它,然后稍后保存,则可以使用保存。

I think that the reason this does not work is because current_user is a method that is not defined on a reviewable. 我认为这不起作用的原因是因为current_user是一个未在可审阅的上定义的方法。

The reviewable may belong to a user, in which case @reviewable.user.reviews.create... may be valid. 可审阅者可能属于用户,在这种情况下, @reviewable.user.reviews.create...可能有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM