ruby - Rails: most Quiz attributes passing to params, apart from user_id. Why? -


for testing/learning purposes, have quiz model following attributes (snippet schema.rb):

create_table "quizzes", force: true |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 sent 'new' view, this:

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

when user completes quiz, quizzescontroller#create action triggered:

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

(whether renders 'show' view or default 'create' view, works - while i'm testing , learning, have both views placeholders now)

and post_params method looks 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 tried params.require(:quiz).permit! same result).

the problem is, in view, looks 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 answer1, answer2 etc, attributes, displays user_id attribute nil - despite quiz being set user_id in quizzesscontroller#new action. doing wrong, prevents user_id passing correctly?

if going set user_id current_user.id, i'd suggest adding attribute in create action.

this way don't have worry user input. else, user might abuse change id, quiz gets added user.

first, remove user_id permitted post_params

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

then update create action to:

def create   # mentioned tagcindy, way set association   @quiz = current_user.build_quiz(post_params)    # should re-render new form if there errors   if @quiz.save     render :show   else     render :new   end end 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -