简体   繁体   中英

Polymorphic model user association

Rails 3.2. I am using the following code to associate user_id to the record:

  # 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:

  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. 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. 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.

The reviewable may belong to a user, in which case @reviewable.user.reviews.create... may be valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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