I am having trouble reading the business_id parameter from a form get request.
http://localhost:3000/clients?utf8=%E2%9C%93&client%5Bbusiness_id%5D=toyota&commit=Save+Client
With: params[:business_id]
Why doesn't that work?
Details:
html form:
<%= form_for :client, url:clients_path, method: :get do |f| %>
<%= f.label :business_id %><br>
<%= f.text_field :business_id %>
<%= f.submit%>
<% end %>
The form hits the create controller and redirects back to the original page:
def create
#clients = Client.all
redirect_to controller: 'clients'
end
On the original page reads the url string in the index controller with:
def index
#clients = Client.all
#filters = params[:business_id]
end
#filters comes back as blank unless I hard code a value.
You need to use params[:client][:business_id] as business_id is inside client hash.
Related
Users apply filters in an index page and I need the filters' params to do some background jobs.
I can access the params after the filters are applied as you normally would, but when I try to forward the request.params to the controller action where I launch the background jobs, the params passed in the form's hidden_field no longer is an ActionController::Parameters object but a String instead, which I can't access as I would normally do by it's key.
form:
<%= form_tag admin_users_on_demand_mass_emails_path, method: :get do %>
<%= simple_fields_for :on_demand_email do |f| %>
<%= hidden_field_tag :filters, params[:q].to_unsafe_h %>
<%= f.input :email,
as: :radio_buttons,
collection: options_for_on_demand_emails %>
<% end %>
<%= submit_tag "Enviar emails", class: "btn btn-primary" %>
<% end %>
params before form send:
<ActionController::Parameters {"q"=><ActionController::Parameters {"fname_or_lname_or_email_or_tax_id_number_or_legal_name_cont"=>"", "extra_params"=><ActionController::Parameters {"invoice_status"=>""} permitted: false>, "subscription_payment_type_eq"=>"", "address_province_eq"=>"", "subscription_status_eq"=>"cancelled", "created_at_gteq"=>"", "created_at_lteq"=>""} permitted: false>, "subscription_status_eq"=>"{}", "commit"=>"Filter", "controller"=>"admin/users", "action"=>"index"} permitted: false>
becomes:
{"filters"=>
"{\"fname_or_lname_or_email_or_tax_id_number_or_legal_name_cont\"=>\"\", \"extra_params\"=>{\"invoice_status\"=>\"\"}, \"subscription_payment_type_eq\"=>\"\", \"address_province_eq\"=>\"\", \"subscription_status_eq\"=>\"cancelled\", \"created_at_gteq\"=>\"\", \"created_at_lteq\"=>\"\"}",
"on_demand_email"=>"[FILTERED]",
"commit"=>"Send emails"}
I've tried many different things such as passing request.params.to_unsafe_h (same result) and params.require(:q).permit(params[:q].keys) which results in an error in the view when :q is not present due to the require.
Is there any way to accomplish this or rebuild the params hash after it's been passed as a string?
You can use JSON.parse() to convert them into hash like below,
{"filters"=>
JSON.parse("{\"fname_or_lname_or_email_or_tax_id_number_or_legal_name_cont\"=>\"\", \"extra_params\"=>{\"invoice_status\"=>\"\"}, \"subscription_payment_type_eq\"=>\"\", \"address_province_eq\"=>\"\", \"subscription_status_eq\"=>\"cancelled\", \"created_at_gteq\"=>\"\", \"created_at_lteq\"=>\"\"}"),
"on_demand_email"=>"[FILTERED]",
"commit"=>"Send emails"}
In the end I did params.permit(q: params.dig(:q)&.keys
I am completely new to RoR and was trying to build a simple blog, but already got stuck at the "Adding Post" function.
The following Error Message pops up when I load .../posts/new:
No route matches {:action=>"show", :controller=>"posts"} missing required keys: [:id]
Here is what my posts controller looks like this:
class PostsController < ApplicationController
def index
end
def new
end
def create
render plain: params[:post].inspect
end
end
Here is what my new.html.erb looks like this:
<h1>Add Post</h1>
<%= form_for :post, url: posts_path do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
I had set posts as resource in my routes. The surprising thing is, that on my friend's laptop, the code works.
I would be very happy about any advice, and apologize for the silly question.
The form_for helper is looking for a resource object to operate with, and you're giving it a symbol. I suspect it's assuming that's an action URL instead, and translating (or trying to) that symbol into a route.
Using form_for in a new action, the pattern is usually to create a new resource and feed that into the form_for helper:
def new
#post = Post.new
end
<%= form_for #post, url: posts_path do |f| %>
...
<% end %>
Check your routes with:
$rake routes
And you'll see that the posts_path with an id its used to update a "post" and not to create one, you'll also found the path you want to create a new "post".
You might say: but i don't have an update action. If on your routes file you used the resources keyword you do, even if the action itself is missing.
Update:
Remove the
url: post_path
From your form_for call
My recommendation, check out the rails guides on routing.
I'm trying to write an application that will have to interact with POST but I'm having issues accessing the parameters. This is not meant to be useful right now but I'm just trying to flash the result of the form. According to google dev tools, the POST parameter is set to 1.
Here's my routes.rb file
devise_scope :user do
put 'users/toggle_activation' => 'users/sessions#toggle_activation'
get 'users/sign_out' => 'users/sessions#destroy'
post 'pages/home' => 'users/sessions#activities'
end
This is the controller in question
def activities
params.permit(:tennis)
current_user.save
flash[:notice] = params[:tennis]
redirect_to root_path
end
This is the form code
<%= form_for :user do |f| %>
<%= f.check_box :tennis %>
<%= f.submit %>
<% end %>
Any help is appreciated.
If you're using "form_for", then the check_box name will result as "user[tennis]", not just "tennis". View source in your browser and you should see this.
Do something like the following in your controller method (although I'm not sure how it will be called with "form_for :user" because your "activities" route isn't in your routes.rb in the code above):
user_params = params.require(:user).permit(:tennis)
flash[:notice] = user_params[:tennis]
I am very new to Rails and have been having some trouble trying to find tutorials that actually work for me. I am attempting to create a database in MySQL and then allow users to submit information to this database through a form. I was able to create a form using the code below but it only triggers the new method in the Controller and not the create method. Does anyone know why this is happening and/or can guide me to a good tutorial for building forms. I have found some in google but for some reason the syntax never works for me when I try to enter it. Thank you very much in advance for any help you can give.
Controller -
class MessageController < ApplicationController
def new
#message = Message.new
end
def create
#message = Message.new
#message.message=params[:mess]
#message.user=params[:name]
if #message.save
redirect_to "http://itworks.com"
end
end
end
View -
<%= form_for :MessageController do |f| -%>
Message: <%= f.text_field :mess %><br />
UserName: <%= f.text_field :name %><br />
<%= f.submit%>
<% end -%>
Edit - When I change :MessageController to #message or :message I get a syntax error. (syntax error, unexpected keyword ensure, expecting $end. Surprisingly enough the form works with :MessageController but it only triggers the new method not the create method.
form_for expects either an instance of a model, or a symbol representing the name of a variable containing an instance of a model. You've given it the name of a controller.
Use this:
<%= form_for :message do |f| -%>
or thiS:
<%= form_for #message do |f| -%>
Since you're new, let me explain some things for you:
--
form_for
<%= form_for #message do |f| -%>
<%= f.label :mess %>
<%= f.text_field :mess %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
When you use form_for, you basically need to populate it with an ActiveRecord object. Currently, you're using the MessageController class, which is totally wrong. You've already set the #message object in your controller - you just need to populate your form_for method with it
--
Strong Params
Secondly, as I already mentioned in your other question, you need to ensure you're using the strong params functionality of Rails correctly:
#app/controllers/message_controller.rb
Class MessageController < ApplicationController
def create
#message = Message.new(message_params)
#message.save
end
private
def message_params
params.require(:message).permit(:mess, :user)
end
end
I'm still pretty new to Rails as well, but it looks like your syntax for the form_for method is off a bit. Here's the example from the rails guide for form helpers:
<%= form_for #article, url: {action: "create"}, html: {class: "nifty_form"} do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body, size: "60x12" %>
<%= f.submit "Create" %>
<% end %>
And here's the link to the form helper page: http://guides.rubyonrails.org/form_helpers.html
I've found the rubyonrails.org guides to be the best resource for trouble-shooting. The documentation is actually quite good(both extensive and clear).
I guess that maybe caused by the "Strong parameter",
to learn more you can see Strong Parameters by Example here.
In the Messages controller, we could add the strong parameter to it
class MessageController < ApplicationController
def new
#message = Message.new
end
def create
#message = Message.new(message_params)
#message.message=params[:mess]
#message.user=params[:name]
if #message.save
redirect_to "http://itworks.com"
end
end
private
def message_params
params.require(:message).permit(:mess, :name)
end
end
Because you define the #message , so..why not use it?
<%= form_for #message do |f| %>
Message: <%= f.text_field :mess %><br />
UserName: <%= f.text_field :name %><br />
<%= f.submit%>
<% end %>
I've been staring at this for a while and Google hasn't helped much so I'm turning to you guys for help. This should be a pretty simple fix.
The goal of the code is to take an email address from a sign up field and place it in the database.
I think most of what I need is there but I'm getting this error:
undefined method model_name for NilClass:Class
My home.html.erb file contains the following:
<%= form_for(#signup) do |f| %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit "Enter" %>
</div>
<% end %>
The model contains this:
class Signup < ActiveRecord::Base
attr_accessible :email
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates(:email, :presence => true,
:length => {:maxiumum => 40},
:format => {:with => email_regex})
end
The controller contains:
class SignupController < ApplicationController
def show
end
def new
#signup = Signup.new
end
def create
#signup = Signup.new(params[:id])
if #signup.save
else
render 'new'
end
end
end
The problem is most likely because of an instance variable that you're using in your form_for not being set to an ActiveRecord object. It appears that you are setting it correctly in your "new" action, but it's not clear that you're rendering the correct template since you mention the form being in "home.html.erb"?
Either way, ensure that whatever you're using in the form_for is set to a valid ActiveRecord object and your problem may be solved.
In addition, you may want to change your create action to use all the params from the form:
#signup = Signup.new(params[:signup])
Add this to the home action in the pages controller:
#signup = Signup.new
The reason for the error is that you are using #signup in your form, but you didn't define it in your show controller action.