How to stop button being passed with parameters? - ruby-on-rails

I don't know why all of my form's buttons and submits keep passing the button in the Parameters also. An example would be If I use my search form and put in the word "Testing". The result I will get is below:
# Using Bootstrap 3.2.0 and Rails 4.1.1
= form_tag products_path, method: :get do
.input-group
= text_field_tag :query, params[:query], class: 'form-control'
%span.input-group-btn
= button_tag(type: 'submit', class: 'btn') do
Search
Parameters: {"utf8"=>"✓", "query"=>"Testing", "button"=>""}
How can I make it not do that?

The name attribute of button is "button" by default.
You could set it to nil by:
= button_tag(type: 'submit', class: 'btn', name: nil) do

Related

Get directly string from params

I have a text field and i want to process the entry after clicking on submit.
The text field is:
<%= text_field :reason_message, params[:reason_message] , placeholder: "Write a reason" %>
The form is:
<%= form_tag main_admin_controller_path, :method => 'post' do %>
And the submit tag is:
<%= submit_tag "Send", name: 'send', data: { disable_with: "Loading..." },class: 'btn btn-primary btn-xs' %>
To get the entry I take the parameters as:
params["reason_message"]
which is returning an array ["test"] or if nothing is written [""].
How can I get the params directly as a string and not as an array?
Right now I do params["reason_message"].join to get it as a string. Is there another way?

Rails parameters contain backslashes

I am currently working with button_tag to create a remote styled answer submission quiz. When pressing this button, instead of posting the new record, it is throwing an error.
ActiveRecord::RecordNotFound (Couldn't find Answer without an ID):
When looking at the server logs I see it is trying to work with these params when trying to post Parameters: {"{\"answer_id\":59}"=>nil, "id"=>"15"}
What I am looking, or expecting to see is this.
Parameters: {"answer_id"=>"59", "id"=>"15"}
Here is the button_tag I am using.
<% #question.answers.each do |answer| %>
<%= button_tag "#{answer.answer.titleize}", class: 'btn btn-block btn-lg btn-primary', data: {
remote: true,
method: :post,
url: answer_question_path(#question),
params: { answer_id: answer.id }
} %>
<% end %>
Here is my response controller which is responsible for submitting the POST request.
class ResponsesController < ApplicationController
def answer
question = Question.find(params[:id])
answer = question.answers.find(params[:answer_id])
response = question.responses.find_or_initialize_by(user: current_user)
if response.update(answer: answer)
head :ok
else
puts 'Something went wrong chief'
end
end
private
def responses_params
params.require(:response).permit(:user_id, :question_id, :answer_id)
end
end
I have tried using to_json on the parameter with no success and have not been able to find any solution elsewhere on SO or other forums. Any ideas?
This seems to be an issue with button_tag in the feature I am using it for.
button_tag creates a button element that defines a submit button, resetbutton or a generic button which can be used in JavaScript. button_tag is also an action view helper but is defined as a FormTagHelper.
button_to generates a form containing a single button that submits to the URL created by the set of options. button_to is a UrlHelper while button_tag is a ViewHelper.
Below is the button_tag code I was using which was creating the issue described above. Using button_tag fixed my parameters issue and also looks a bit cleaner. I hope this helps anybody else having issues with button_tag in the future.
<%= button_tag "#{answer.answer.titleize}", class: 'btn btn-block btn-lg btn-primary', data: {
remote: true,
method: :post,
url: answer_question_path(#question),
params: { answer_id: answer.id }
} %>
<%= button_to "#{answer.answer.titleize}",
answer_question_path(#question),
class: 'btn btn-block btn-lg btn-primary',
params: { answer_id: answer.id },
remote: true %>

How to make Rails 5.2 form submit remotely?

In my view, using Slim:
= form_with url: update_pn_price_path(#price)
.form-group
= label_tag :part_number
= text_field_tag :part_number, #price.part_number, required: true
.form-group
=> submit_tag t(:save), class: 'btn btn-primary btn-sm'
= link_to 'Cancel', '', class: 'btn btn-link btn-sm', data: { cancel_in_place: true }
This always submits using a standard submit, not remotely. Log shows:
Processing by PricesController#update_pn as HTML
What am I doing wrong? Why won't it submit using JS?
I'm surprised to see that your view compiles. There are a few problems that I can spot.
You start indenting content as though it would be in the form. However you didn't open a form tag or provided a block to the form_with method.
= form_with url: update_pn_price_path(#price)
.form-group
Should at least be changed to:
= form_with url: update_pn_price_path(#price) do
.form-group
Since a variable is provided to a block, the preferred way is to capture it in a variable (form in the code below). If you're not planning to use it you should still capture it in an underscored variable to indicate that it is there, but not being used (_form).
= form_with url: update_pn_price_path(#price) do |form|
.form-group
Since you're using a form builder, the preferred way of creating elements is through the form builder interface. Since you're not creating the submit tag through the form builder this might be another reason why the submit isn't done remotely.
I would at least replace:
=> submit_tag t(:save), class: 'btn btn-primary btn-sm'
With:
= form.submit t('save'), class: 'btn btn-primary btn-sm'
But preferably update the whole form to use the form builder. The result should look something like this:
= form_with model: #price, url: update_pn_price_path(#price) do |form|
.form-group
= form.label :part_number
= form.text_field :part_number, required: true
.form-group
= form.submit t('save'), class: 'btn btn-primary btn-sm'
= link_to 'Cancel', '', class: 'btn btn-link btn-sm', data: {cancel_in_place: true}
For more/other form builder methods see the FormBuilder and FormHelper documentation.
Here's what solved the issue. Rookie mistake, but posting here in case someone else runs into it.
My form shown above was inside another form. You can submit such an 'inner' form, but not remotely. The form was being inserted via an AJAX call, so I changed that to insert to the end of the HTML body, and then positioned using CSS. That put it outside the containing form and made things work as expected.

Cannot set form_tag method as get

I try to send a form_tag with get method like this
= form_tag search_offers_path, method: :get, class: 'sort-form form inputs-underline' do
.sort-inputs
.input-group.inputs-underline.min-width-150px.sort-input
= label_tag :sort_by, 'Sort by'
= select_tag :sort_by, options_for_select([["Sort by", ""], ["User level", "user_level"], ["Success rating", "user_average_overall_rating"]]), class: "form-control"
.input-group.inputs-underline.min-width-150px.sort-input
= label_tag :sort_direction, 'Sort direction'
= select_tag :sort_direction, options_for_select([["Sort direction", ""], ["Ascending", "asc"], ["Descending", "desc"]]), class: "form-control"
But I don't understand why it becomes a POST as form_tag default
Started POST "/offers/search" for 127.0.0.1 at 2018-01-04 12:35:18 +0700
ActionController::RoutingError (No route matches [POST] "/offers/search"):
Anyone has a hint?
UPDATE: I checked the HTML generated based on the feedback and see that data-remote = true (although I have never set it and I don't want an ajax request, too).
<%= form_tag({}, {:method => :get, class: 'sort-form form inputs-underline'}) do %>
Try this one. You can definitely get your solution.

rails 4 update user profile by button

hy, i'm trying to update a single field in a user resouce. The field to update is 'locale', it is a string type.
i have triend with a form and it works:
<%= form_for current_user do |f| %>
<%= f.select :locale, [['En', 'en'], ['It', 'it']] %>
<%= f.submit %>
<% end %>
now i'm trying to update the same field using a link or a button:
<%= current_user.locale = 'fr' %>
<%= button_to "update" ,current_user,method: :patch %>
<%= button_to "update" ,user_path(current_user),method: :patch %>
but none of this work.
the problem is the request, infact the web server doesn't recive the current_user parameters:
{"_method"=>"patch",
"authenticity_token"=>"7X6QdD4DGxsXaETT86/8Ut4xyuOICaxirs4IjmZl7jY=",
"locale"=>"en",
"id"=>"1"}
There is no current_users parameters.
i have tried with the link_to but the problem is the same:
<%= link_to "update", current_user ,method: :patch %>
I have no idea. Can you help me?
The fact that you don't get the parameter sent back to server is the expected one since you don't use a form.
In order to pass the parameter back you have to:
use a form (as you did) or
pass the parameter in the url of the button: button_to 'update', user_path(param_name: 'param_value')
In the second case, you will have to search for the appropriate parameter in your action, ex params[:param_name]

Resources