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