2

For testing/learning purposes, I have a Quiz model with the following attributes (snippet from schema.rb):

create_table "quizzes", force: true do |t|
    t.integer  "user_id"
    t.string   "answer1"
    t.string   "answer2"
    t.string   "answer3"
    t.string   "answer4"
    t.string   "answer5"
    t.string   "answer6"
    t.string   "answer7"
    t.string   "answer8"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "quizzes", ["user_id"], name: "index_quizzes_on_user_id"

A Quiz is sent to the 'new' view, like this:

def new
    @quiz = Quiz.new(user_id: current_user.id)
end

When a user completes the quiz, the QuizzesController#create action is triggered:

def create
    @results = Quiz.create(post_params) #from private method
    render :show
end

(Whether this renders the 'show' view or the default 'create' view, it works - while I'm testing and learning, I have both those views as placeholders for now)

And the post_params method looks like this:

def post_params
    params.require(:quiz).permit(:user_id, :answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8) #add other attributes here
end

(I have also tried params.require(:quiz).permit! but I get the same result).

The problem is, in the view, which looks like this:

<div class="container">
      <!-- Example row of columns -->
      <div class="row">
        <h1>Results</h1>
        <p><%= @results.inspect %></p>
    </div>
</div>

...the @results.inspect line displays all the answer1, answer2 etc, attributes, but displays the user_id attribute as nil - despite the Quiz being set up with a user_id in the QuizzessController#new action. What am I doing wrong, that prevents the user_id passing correctly?

3 Answers 3

2

If you are always going to set the user_id to the current_user.id, I'd suggest adding that attribute in your create action.

This way you don't have to worry about user input. Else, a user might abuse this to change the id, so the quiz gets added to another user.

First, remove the user_id from the permitted post_params

def post_params
  params.require(:quiz).permit(:answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8)
end

Then simply update your create action to:

def create
  # as mentioned by tagCindy, this is the way to set up the association
  @quiz = current_user.build_quiz(post_params)

  # you should also re-render the new form if there are any errors
  if @quiz.save
    render :show
  else
    render :new
  end
end
5
  • 1
    Thanks for the reply! I've used @results = Quiz.create(post_params.merge(:user_id => current_user.id)) and that seems to have done the trick! (.create saves the object as well, I think, so I don't need most of the other lines). Thanks again. Dec 16, 2014 at 15:40
  • Had to downvote this answer because it ignores the need to properly associated User to Quiz.
    – tagCincy
    Dec 16, 2014 at 15:55
  • that's ok, why is current_user.quizzes.create(quiz_params) better?
    – davegson
    Dec 16, 2014 at 15:58
  • I believe that save calls valid?. so no need for the @quiz.valid? just: if @quiz.save
    – DickieBoy
    Dec 16, 2014 at 16:09
  • 1
    @TheChamp the means on which you do the association adds a level of unnecessary complexity on to the logic. Unnecessary complexity injects a greater chance of an exception being hit. For example, if post_params is malformed, nil or otherwise not a copacetic strong_params hash, the user is going to get an error on the .merge operation instead of an expected validation error. I have regularly used that methodology to inject extra data into the params hash, so that in and of itself is not wrong. But if ActiveRecord gives you the means to streamline the association, I suggest using it.
    – tagCincy
    Dec 16, 2014 at 16:24
2

First off, review ActiveRecord associations. There should be an association between your Quiz model and your User model (either many to one, or one to one). If the association is set up correctly, and the current_user data is saved to the session, there is no need to pass the user_id with the POST.

class QuizzesController < ApplicationController
# grabs the current_user from the session
before_filter :get_current_user

# ...

def create
    # METHOD 1: initialize and persist, check for errors
    @quiz = current_user.create_quiz(quiz_params)
    if @quiz.errors
        render :new
    else
        redirect_to @quiz # or where ever

   # METHOD 2: initialize, check for successful save
   @quiz = current_user.build_quiz(quiz_params)
   if @quiz.save
        render :new
    else
        redirect_to @quiz # or where ever
end

# ...

private

def get_current_user
    @current_user = User.find(session[:user_id])
end

def quiz_params
    params.require(:quiz).permit(:answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8)
end

end

If you do not wish to store the user_id in the session, I would set up your routing so that the user_id is passed to the controller in the route. Passing the user_id as a hidden value on the form should be avoided at all cost as it is not secure and can be easily manipulated and/or spoofed.

On a side note, you should have an Answer model with a many to one relationship to Quiz.

8
  • I know I should have Quiz has_many :quiz_answers, but I'm trying to set it up a step at a time as simply as possible. In my Quiz model it belongs_to :user and in User it has_one :quiz. At what point can I refer to current_user.quiz? Does a model of a Quiz have to have been set up on the current_user or is that the wrong way to think about it? When I tried current_user.quiz.build(..etc..) it threw a current_user.quiz = nil error. Dec 16, 2014 at 16:00
  • Since User has_one :quiz, I've just tried @results = current_user.quiz.create(post_params) (with the post_params method as it is in the original question, minus user_id) but that also throws a "undefined method 'create' for nil:NilClass", so it looks like current_user.quiz is nil at that point. Dec 16, 2014 at 16:08
  • has_one does not have a create or build method; you need to use create_quiz or build_quiz. See my updated answer.
    – tagCincy
    Dec 16, 2014 at 16:19
  • hey, I like this answer. With my answer, would it be possible to create multiple quizzes though the relationship is has_one?
    – davegson
    Dec 16, 2014 at 16:22
  • 1
    @TheChamp no, you would hit an exception if you attempted to save a second quiz to an user
    – tagCincy
    Dec 16, 2014 at 16:26
0

Thats because post_params is meant to handle parameters that are given to the controller. i.e. POST/GET

user_id (i assume) isn't in your form therefore not given to the controller via the form.

What I would do is:

def create
  @results = Quiz.create(post_params.merge(user_id: current_user.id) #from private method
  render :show
end

Even better provided you have the relationships setup correctly(singularize quizes if its a 1>1):

def create
  @results = current_user.create_quiz(post_params) #this will fill in the user_id field for you
  render :show
end

In your form, DO NOT do:

= f.hidden_field :user_id, current_user.id

Doing this means that any user can create quizes for any other user.

5
  • 1
    in your second solution, don't you have to save the build? I don't think this is done automatically
    – davegson
    Dec 16, 2014 at 15:28
  • User has_one :quiz, so it doesn't like the current_user.quizzes.build(post_params) line. Also, if I change it to current_user.quiz.build(post_params) I get an error saying .quiz is nil (I'm guessing as this hasn't been set up on the user yet). If I'm wrong about why that error happens, please let me know... Dec 16, 2014 at 15:30
  • @moosefetcher you are correct it will be nil. I did say assuming you have your relationships setup correctly.
    – DickieBoy
    Dec 16, 2014 at 16:09
  • That's not to say User has_one :quiz is the wrong association, right? Just that you thought it might be something else... Dec 16, 2014 at 16:36
  • @moosefetcher Sorry I was wrong, has_one relationships don't have a build method. God knows why. I have edited my answer.
    – DickieBoy
    Dec 16, 2014 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.