简体   繁体   中英

Ruby on Rails 4 - How do I iterate through these params?

I have the following params that are being submitted:

{"utf8"=>"✓", 
"course"=>
   {
    "title"=>"Test", "roles"=>["Tuesday", "Thursday"]
   }
}

My question is: How do I iterate through the "roles" params to "add_role"?

I am currently trying this iteration, but it is not working:

@course.user_id = current_user.id

params['course']['roles'].each do |key, value|
  @course.add_role(key['course']['roles'])
end

I get the following error: undefined method '[]' for nil:NilClass

What am I doing wrong with iterarting the params?

Thank you!

params['course']['roles'] is the array ["Tuesday", "Thursday"] , not a hash.

In your loop, key takes the value of a role string, "Tuesday"['course'] returns nil and nil['roles'] causes your error.

You seem to be trying to do this:

params['course']['roles'].each do |role|
  @course.add_role(role)
end

irb

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