Jeremy Lynch
Jeremy Lynch

Reputation: 7210

Pass array of parameters to a link

Consider the following rails link:

search_path(:query => params[:query], type: params[:type], sort: params[:sort])

There is a lot of duplication here. Is it possible to define these parameters in an array and they pass into the link? Eg.

params: [:query, :type, :sort] # -> pass each into the link like "key: value" 

Upvotes: 0

Views: 96

Answers (1)

treiff
treiff

Reputation: 1306

I can't think of how you could do it exactly passing it as an array like you show, however you could do something like:

search_path(params.slice(:query, :type, :sort))

This will give you the same hash you're passing in. In my opinion, it's a little cleaner.

parameters = ActionController::Parameters.new(query: 'query', type: 'type', sort: 'sort', other: 'other')
=> {"query"=>"query", "type"=>"type", "sort"=>"sort", "other"=>"other"}

parameters.slice(:query, :type, :sort)
=> {"query"=>"query", "type"=>"type", "sort"=>"sort"}

Upvotes: 2

Related Questions