How do I build link with specific part of params hash from previous request? - ruby-on-rails

While I wouldn't normally create a page like this, please know this is a current constraint I can't change.
The page has a checkbox form as well as a table with links for THs that sort the table. I need to construct the TH link in a way that it retains the checkbox items already checked.
Checkbox constructed in View with Haml as:
= form_tag movies_path, :method => :get do
Include:
- #all_ratings.each do |rating|
= rating
= check_box_tag "ratings[#{rating}]", "1", (#ratingsarray.include?(rating) ? true : false)
= hidden_field_tag 'sort', #sort
= submit_tag 'Refresh'
Then for the table it has this for the TH
%th{:class => #classrelease_date}
%a#release_date_header= link_to "Release Date", movies_path(:sort=>'release_date', :params[:ratings]=>params[:ratings])
Ultimately I want the URL like "/moves/?sort=release_date&Ratings[PG]=1&Ratings[G]=1" where I am spitting out the ratings params back to the page as part of the URL. Or how to I pass the ratings params in any part of page where the existing controller code will read it.
Existing controller code access ratings from checkbox:
params[:ratings]

Since movies_path accepts hash as parameter, you can tailor params and then generate the URL with movies_path(params). Generally, you may need to remove "controller" and "action" from params.

Related

Rails - Merge Multi-Select Params into comma-separated string

I have a select box that allows multiple values, to filter the results on the page. When I select multiple, the Parameters that are submitted look like this:
Parameters: {"categories"=>["books", "films"], "commit"=>"Submit", "id"=>"87"}
When I am returned to the page, the URL is:
http://localhost:3000/87/projects?categories%5B%5D=books&categories%5B%5D=films&commit=Submit
The URL I would like to return is:
http://localhost:3000/87/projects?categories=books,films
How can I return these params[:categories] as a comma-separated string in the URL? Also, is it possible to remove the "&commit=Submit" from the URL?
Here is my full form code:
<%= form_with url: project_path(#project), local: true, method: :get, skip_enforcing_utf8: true do |form| %>
<%= form.select(:categories, #categories.map {|category| [category.name,category.slug]}, options = { selected: params[:categories], include_blank: "Select Categories", include_hidden: false }, html_options = { multiple: true }) %>
<%= form.submit 'Submit' %>
There's a couple JS & Rails way to do what you want. I can think of a quick and easy one using rails only: Redirecting the URL you are getting to another route with the data parsed as you want it. Like this -->
Assuming this is your route to project_path : get 'project', to: 'project#reroute', as: :project
You can go to your reroute method in the project controller and parse the data you got.
project_controller.rb
class ProjectController < ApplicationController
def reroute
redirect_to your_path(categories: params[:categories].join(','))
end
end
This converts your categories array to a string with your values separated by commas. It is not an array anymore. and it also removes "&commit=Submit" like you wanted.
If you dislike the rails routing method, you can also make your submit button to run some JS functions that builds the url string as you want it. For example <%= submit_tag , :onclick => "return buildUrl();" %>
Having this said, I must say I agree with Edward's comment, the url encoded format is standard and works out of the box, no need for all the additional rerouting and parsing. Im pretty sure whatever you need the data for can be used with the URL encoded format with proper parsing.

Ruby On Rails: How to pass an Input value from a form to a controller in a link_to tag?

I have a form with input tag which takes a value from the user and next to that there is a link which should take that value and pass it to a method in a controller which generates an encrypted values based on that hash.
However params[:hash] which is my input does not pass input to controller. gives NULL. Please look in to my code and let me know where I am going wrong.
thanks
view:
= simple_form_for(#user, :html => {:class => 'user_form'}) do |f|
= f.input :hash, :input_html => {:class => 'span4'}
= link_to('Click to confirm key Encryption',confirm_encrypt_path(#user,:hash=>?)
controller:
def confirm_encrypt
check = params[:hash]
puts check # gives null value
MyModel.reset_authentication_pin!(current_user.id,params[:hash])
end
I Expect the puts check value should be the user entered value.
It's hard to tell what's happening here because it appears you've only included a portion of the view, if you could edit your question, that might help shed some light on what else is happening.
Three things that stand out to me are:
In your view you call the input :hash, but when you attempt to get the value you get params[:temp1] not params[:hash]
In the link_to you include the user, but you don't include any value for the :hash. Off the top of my head, I believe you just need to do params[:hash] to successfully get the :hash value through to the controller with the way you have it.
In your view you set up a simple_form_for, but it appears that you don't use a submit to get the :hash value in the controller. If you decided to go that route, you'd just have to make sure that the form is being directed to the proper controller.

How to add a search parameter to an existing Ransack query

I have a search form on a page, that allows a user to filter a list on multiple conditions. Now I'd like to add quick links on top of the list to apply scopes. I tried it like this:
= link_to "Visited", q: {"activated" => true}
While this filters the list to show only activated items, it also resets the search query. In other words, it doesn't remember what was already filtered in the form.
Is there a way to adapt #q so that I can add this "activated" => true to the hash of required filters?
Assuming you're only using the :q param to filter, you could aggregate that.
= link_to "Visited", q: (params[:q] || {}).merge(activated: true)
I don't think you can because if you follow a link you are not submitting the form therefore the parameters are not going to be submitted.
Passing the params in your link to will send the params if any exist:
= link_to "Visited", q: {"activated" => true, "your_params" => params}
This will only work if the form has been submitted once though, otherwise the params would be empty.
EDIT
I assume that the fields on your forms are populating if there is a value.
For example,
<%= text_field_tag(:email, if !params["email"].nil? then params["ip_email"] end) %>

Simple rails filters

I have simplest rails app, with scaffold Tent
here my controller#index for
def index
#tents = Tent
#tents = #tents.where(:brand => params[:brand]) if params[:brand]
#tents = #tents.where(:season => params[:season]) if params[:season]
end
view also standart, generated by scaffold
and here search witch should filter data
= form_tag tents_path, method: :get do
= label_tag "manufacturer"
= select_tag :brand, options_for_select(...), include_blank: true
= label_tag "seasons"
- Tent.pluck(:season).each do |season|
=check_box_tag 'season', season
=h season
= submit_tag 'Submit'
Problem 1:
When i submit from, and params are unselected(select or checl_boxes) i don't want to send this params but they are sent with empty
GET /tents?utf8=...&brand=&season=&commit=Submit
Problem 2:
When i check multiple checkboxes get request is somthing like
GET /tents?utf8=...&brand=Brand&season=4&season=3&commit=Submit
after this i expect that data will be selected for both values, but controller expected that both values is in the field, and returns zero results
any suggestuions?
UPDATE
probably my question solved in railscasts-111 (advanced search form)
About problem 2:
You need to specify season checkbox like below:
=check_box_tag 'season[]', season
But i didnt test it
Problem 2:
You need to write javascript wrapper for form to serialize and send data on submit

rails 3, any way to add a row identifier (or query param) to submit_tag? (how identify the row being submitted?)

What is 'the rails way' to have a form with submit_tags for each row, where the submit_tag 'tells' the controller which row's submit was clicked?
Inside a form_tag, my form displays a list of users, and next to each user are several actions such as 'foo' and 'bar'.
Currently I use link_to for those actions, which adds a query param :row => this_row.guid so my controller knows which row to take action on. It works, but I don't like having the query params exposed on the url, and I don't like how they persist on the URL so if the user clicks refresh it performs the action again.
Since the rows are displayed are inside a form already, I'd like to have each action be a submit_tag. But I do not see from the API docs that there is any way to add a different query param to each instance of a submit_tag.
When I try this:
= submit_tag "foo", {:row => this_row.guid}
= submit_tag "bar", {:row => this_row.guid}
The html DOES look like <input .... row='SOMEGUID' ...>
However the POSTed params do not include the :row query params
I also tried
= submit_tag "foo", params.merge(:row => this_row.guid)
= submit_tag "bar", params.merge(:row => this_row.guid)
with the same result ( includes the row=GUID, but that param is not POSted to the controller when the user clicks the submit button).
I'd appreciate any help on how to have many rows of submit buttons (with the same name visible to the user) also pass a row identfier to the controller.
the value of the submit button also gets sent as a parameter. check your logs.
UPDATE
Add the row id as a data attribute of the submit button:
= submit_tag "bar", {:data => {:row => this_row.guid}}
Then when the submit button is clicked it should add the row id as a hidden field in the form before it gets submitted.
$('input[type="submit"]').click(function(){
$('form').append('<input type="hidden" name="row" value="' + $(this).data('row') + '" />');
});

Resources