Passing text field value to Rails Controller - ruby-on-rails

I'm fairly new to Rails and I'm stuck with passing a text field value to Rails Controller method. Any help is appreciated, below is my code..
View code:
Upon click of the below button I want to be able to send the username to the Controller method..
<%= link_to "My button", admin_user_creds_path(user_config),
method: :test_user, role: "button" %>
The username is entered in a text field:
<%= form_for [:admin, user_config] do |f| %>
<td class="js-editable-text rf-table__td rf-table__col--username">
<div class="preview js-preview show"><%= user_config.username %></div>
<div class="js-input hide"><%= f.text_field :username, class: "form-control" %></div>
</td>
My routes file:
post "/user_configurations/:id", to: "user_configurations#test_user", as: "user_creds"
My controller:
def test_user
username = user_params[:username]
end
def user_params
params.require(:user_configurations).permit(:username)
end

Instead of using link_to helper you need add a submit button to your form.
<%= form_for [:admin, user_config] do |f| %>
<td class="js-editable-text rf-table__td rf-table__col--username">
<div class="preview js-preview show"><%= user_config.username %></div>
<div class="js-input hide"><%= f.text_field :username, class: "form-control" %></div>
<%= f.submit "My button" %>
</td>
Also please note that method option in link_to helper is either get or post HTTP methods but not the controller action

Related

using an instance of appointment in the appointment model

I've created a form with some radio buttons and had to interpolate the appointment.id into the radio button and the label. However, Rails is throwing the error:
undefined method cancel_3 for Appointment.
So I have tried to make a method in the Appointment model to solve this by using define_method (see below). However as this is in the model, I'm unable to use the instance of appointment here.
Is there any way I can make this work?
define_method "cancel_#{appointment.id}" do
# ...
end
<%= f.radio_button "cancel_#{appointment.id}", :true %>
<%= f.label "cancel_#{appointment.id}_true", "Yes", class: "modal-options cancel" %>
<%= simple_form_for :appointment, url: delete_admin_appointment_path(appointment) do |f| %>
update your form with
<%= simple_form_for #appointment, url: delete_admin_appointment_path(#appointment) do |f| %>
and in your controller
def new
#apointment = Apointment.new
end
and radio button with
<%= f.radio_button "cancel_#{#appointment.id}", :true %>
<%= f.label "cancel_#{#appointment.id}_true", "Yes", class: "modal-options cancel" %>

rails one search field handled by two controllers

In my app I want to set a search form with two buttons. Each one of those buttons should send request to separate controller. Something like this:
<%= form_tag(products_path, method: :get) do %>
Search Field <%= text_field_tag :q %>
<br>
<%= submit_tag 'First controller' %>
<%= submit_tag 'Second Controller' %>
<% end %>
Is this even possible? Or rails just impose on developer an "one form - one controller" way?
Use JavaScript to change the form URL based on the button clicked.
<%= form_tag(first_controller_path,id: 'search-form', method: :get) do %>
Search Field <%= text_field_tag :q %>
<br>
<button type='submit' id="form-submit-button">First Controller</button>
<button type='button' id="second-controller-button">Second Controller</button>
<% end %>
<script>
$(function(){
$("#second-controller-button").on("click",function(e){
e.preventDefault();
var form = document.getElementById('search-form');
form.action = '<%= second_controller_path %>' ;
form.submit(); // Or you could also try document.getElementById("form-submit-button").click();
})
});
</script>
HTML5 added some attributes to INPUT and BUTTON elements. One of them is formaction so you can set the action triggered by each button independantly and it overrides the default form action.
<%= form_tag(products_path, method: :get) do %>
Search Field <%= text_field_tag :q %>
<br>
<%= submit_tag 'First controller' #triggers the default action %>
<%= submit_tag 'Second Controller', formaction: another_path %>
<% end %>
https://www.w3schools.com/tags/att_input_formaction.asp
You already defined form_tag with products_path through which the controller method is already defined.
So answering your question, you can't pass send requests to two different controllers with one form.
If you want to pass some status with buttons try adding some attributes to the buttons and differentiate them inside the controller.

No post parameters sent when a form is submitted

I have a model called AlphaUser. When I submit a form to create a new alpha user, I'm told there wasn't any data in the params[:post]. How can this happen?
My code for the form:
<%= form_for :alpha_user,
url: alpha_users_path,
class: "form",
id: "alphaTest" do |f| %>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field :email,
class: "form-control", placeholder: "grandma#aol.com" %>
<%= f.text_field :producer,
class: "hidden", value: "0" %>
</div>
<%= f.submit "Request Access", class: "btn btn-primary" %>
<% end %>
My controller:
class AlphaUsersController < ApplicationController
def create
render text: params[:post].inspect
end
end
Data is still recieved, just in this format:
{"utf8"=>"✓", "authenticity_token"=>"blahblahblah", "alpha_user"=>{"email"=>"test#test.com", "producer"=>"0"}, "commit"=>"Request Access", "action"=>"create", "controller"=>"alpha_users"}
You need to call params for the :alpha_user... e.g. params[:alpha_user].
If you're using strong_parameters in Rails 4, this should do the trick:
class AlphaUsersController < ApplicationController
def create
#alpha_user = AlphaUser.new(alpha_user_params)
#alpha_user.save
end
private
def alpha_user_params
params.require(:alpha_user).permit(:email, :producer)
end
end
Notice that in your create action you are no longer referencing the params directly, but the alpha_user_params method required by strong_parameters.
Check this answer: Custom name for params hash from Rails form_for
Also there's a reason for this naming convention. Look here through section 7 "Understanding Parameter Naming Conventions".

Why is my one form submitting both the forms on this page?

I have two forms that I want to be submitted from new.html.erb, which is served by status_updates Controller. The init form, and the the stat form.
When I submit the stat form, everything works perfectly.
The init form has a different controller it answers to. The problem is that when I submit this form it immediately tries to find the object for the stat form within the controller for the init form.
If I go to that controller and provide the an instance of the object, it'll submit both forms.
Here's the error when I submit the init form.
undefined method `model_name' for NilClass:Class
<div id='stat'>
<%= form_for(#status_update) do |f| %>
The stat form submits fine. When the init form is submitted it tries to process the stat form as well. If I provide the model #status_update within init's action controller it will submit both forms. If not, it throws the above error.
Here's the code for init form
<div id='init'>
<%= form_for(current_user, method: :put ) do |f| %>
<%= f.label :target_bf_percent %>
<%= f.text_field :target_bf_pct %>
<%= f.label :Deficit_percent %>
<%= f.text_field :deficit_pct %>
<%= f.label :activity_factor %>
<%= f.select( :activity_factor, options_for_select(
[['Pick One', nil],
['Sedentary (Desk Job)', 1.2],
['Light Activity (1-3 day a week)', 1.35],
['Moderate Activity (3-5 days a week)', 1.55],
['Very Active ( 6-7 days a week)', 1.75],
['Extremely Active (Atheletic Endurance)', 1.95]]) )
%>
<%= f.submit "Post", class:"btn btn-large btn-primary" %>
<% end %>
</div>
And the code for the stat form
<div id='stat'>
<%= form_for(#status_update) do |f| %>
<%= f.label :current_weight %>
<%= f.text_field :current_weight %>
<%= f.label :current_bf_pct %>
<%= f.text_field :current_bf_pct %>
<%= f.submit "Post", class:"btn btn-large btn-primary" %>
<% end %>
The status_update controller new action:
def new
#status_update = current_user.status_update.build if user_signed_in?
end
The users controller update action:
def update
if current_user.update_attributes!(params[:user])
flash[:success] = "Your personal settings have been saved!"
render new_status_update_path
else
flash[:error] = "Whoops! There was an error saving your personal settings. Please try again."
render new_status_update_path
end
end
Please let me know of anything I can do to improve this question.
It doesn't matter if you render one or more forms on the same page.
Your problem is caused by #status_update because it is nil, but you already know that.
Double check if it is initialized in your controller.

Rails : How to use an object along with a text_area_tag of form_tag?

<%= text_area_tag :body_html, "", :class =>"required mceEditor", :id=>"txaEditableContent" %>
This is my code. I want this text_area_tag to be assigned to an object(object is note in my case) just like we use "form_for object" so that the :body_html goes straight into params[:note] on submit. How can I do this?
You have got to set first an instance of Note in the controller corresponding action:
#note = Note.new
Then, in your view put this form:
<%= form_for #note do |f| %>
<%= f.text_area :body_html, :class => "required mceEditor", :id => "txaEditableContent" %>
<%= f.submit "Submit" %>
<% end %>
Now when you click the submit button you should get the right post request as you needed.

Resources