wind
wind

Reputation: 440

how to get the parameters in Ruby on Rails?

I want to get the value of material_sort_id

Started GET "/materials?utf8=%E2%9C%93&material%5Bmaterial_sort_id%5D=1&material%5Bbrand_id%5D=1&commit=%E6%9F%A5%E8%AF%A2" for 127.0.0.1 at 2015-05-28 16:06:34 +0800
Processing by MaterialsController#index as HTML
        Parameters: {"utf8"=>"✓", "material"=>{"material_sort_id"=>"1", "brand_id"=>"1"}, "commit"=>"查询"}

this is my code :

puts params[:material_sort_id].present?

I got false. How do I get it?

Upvotes: 0

Views: 111

Answers (4)

Amit Sharma
Amit Sharma

Reputation: 3477

According to the logs

"material" => {"material_sort_id"=>"1", "brand_id"=>"1"}, "commit"=>"查询"}

Your params[:material_sort_id] is inside the "material" key so you can't access directly. It's something like you have 2 Hash the 1st Hash key contains another Hash

e.g { "a" => { "b"=> "1", "c" => "2" } }

To access you can use following.

params[:material][:material_sort_id]

To Check whether its present or not you can use following.

params[:material][:material_sort_id].present?

Upvotes: 1

Don Lee
Don Lee

Reputation: 463

Loop 
{
    //Code   
    puts params[:material][:material_sort_id];
}

Upvotes: 1

Triveni Badgujar
Triveni Badgujar

Reputation: 941

It might possible that url is not having material hash itself. In that case you can write

params[:material].try(:material_sort_id)

In above case it will query material_sort_id on material only if material hash is not nil. If it is not nil it will return expected result else return false instead of any error

Upvotes: 0

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

params[:material][:material_sort_id]

You can get it like this

Upvotes: 6

Related Questions