Pre-populating a form field from a link - ruby-on-rails

I'm trying to pre-populate a string field in a form when a link is clicked. I've tried:
$<%= link_to "New product", new_product_path(:product_name => "foo") %>
and
$<%= link_to "New product", new_product_path(:name => "foo") %>
Both didn't work. Anyone has any idea?

Try this,
<%= f.text_field :name,:value=>(#product.new_record? ? params[:name] : #product.name )%>
or in new action
def new
#product = Product.new(:name=>params[:name])
end
<%= f.text_field :name %>

I think this is best done from the controller. You can control what you send via the link_to as before.
class ProductsController < ApplicationController
def new
#product = Product.new new_product_params
end
def new_product_params
params.permit :name, :another_field
end
end

Is the field you're trying to populate on the current page, or the target page?
If it is on the current page you'll need some javascript to accomplish that, if its on the
target page you should probably set the default in your action based on passed parameters.

Related

Search form Couldn't find User with 'id'=

I need to create search form to search for all the cases pt_name of the user
I got this error
Couldn't find User with 'id'=
In cases controller
def index
#user =User.find(params[:id])
#cases=#user.cases
if params[:search]
#search_term = params[:search]
#cases= #user.cases.casesearch_by(#search_term)
end
end
in case model
class Case < ActiveRecord::Base
belongs_to :user
def self.casesearch_by(search_term)
where("LOWER(pt_name) LIKE :search_term OR LOWER(shade) LIKE :search_term",
search_term: "%#{search_term.downcase}%")
end
end
in cases index.html.erb
<%= form_for "",url: cases_path(#user.id), role: "search", method: :get ,class: "navbar-form navbar-right" do %>
<%= text_field_tag :search, #search_term,placeholder: "Search..." %>
<% end %>
The problem is the first line in your controller.
When the form is submitted it's going to cases_path(#user.id) - that's what you specified in your form.
If you're checking with rails routes you'll see that cases_path is actually going to "/cases" (I am assuming you did not overwrite it) and that there isn't any placeholder for an id (like it would be for the show action for example which goes to "/cases/:id".
Now you still specify #user.id in cases_path(#user.id) and then you try to find a user with the id from the params. But if you check your params once you arrived in the controller (with binding.pry or other tools), you will see there is no key :id in the params. You can also check the url it is going to, I believe it will look something like this: "/cases.1".
You can solve that by changing the path to
cases_path(user_id: #user.id)
This way you add a new key value pair to the params hash and then in your controller you need to change it accordingly:
#user =User.find(params[:user_id])
You can also add a hidden field into your form in order to pass along the user id:
<%= form_for "", url: cases_path, role: "search", method: :get, class: "navbar-form navbar-right" do %>
<%= text_field_tag :search, #search_term,placeholder: "Search..." %>
<%= hidden_field_tag :user_id, #user.id %>
<% end %>
And then retrieve it in the controller.
To check your params that you get in the controller action use a gem like pry byebug or just the keyword raise and then inspect the params variable.

Ruby on Rails form param is missing or the value is empty. But value is set

I'm trying to submit a form in ruby on rails that i made, but keep getting de next error.
Ruby on Rails form: param is missing or the value is empty
my form
<%= form_for #test do |f| %>
<div class="field">
<%= f.text_field :first_name %><br>
<%= f.text_field :last_name %><br>
</div>
<div class="actions">
<%= f.submit "Create" %>
</div>
<% end %>
my controller
def new
#test = Test.new
end
def create
#test = Test.new(allow_params)
if #test.save
redirect_to 'test/index'
else
render 'test/new'
end
end
private
def allow_params
params.require(:last_name).permit(:first_name)
end
my routes
resources :test
get 'test/index'
get 'test/new'
get 'test/create'
post '/tests' => 'test#create'
Your attributes are within the testlabel, so here you should go :
def allow_params
params.require(:test).permit(:first_name, :last_name)
end
Look, this is what you form posts when you click submit:
{"utf8"=>"✓","authenticity_token"=>"...", "test"=>"first_name"=>"poldo", "last_name"=>"de poldis"},"commit"=>"Create"}
As you can see first_name and last_name are inside an hash as value of a key called test. Indeed your function allow_params expects something like this
last_name: {first_name: 'poldo'}
as you can see the param (last_name) is missing, because is inside test!
The right way is as Ben answered:
params.require(:test).permit(:first_name, :last_name)
To understand better how strong parameters works I suggest to you to check this page Api doc or even better The latest version ofthe official manual

Rails form_tag not displaying the existing field value

I've a settings controller setup like this:
class Admin::SettingsController < ApplicationController
def index
#settings = Setting.all
end
def update
setting_params.each do |key, value|
Setting.where(key: key).first.update_attribute :value, value
end
redirect_to admin_settings_path, notice: "Settings saved."
end
private
def setting_params
params.require(:settings).permit(:site_title, :site_desc)
end
end
The index action has a view file in relevant path, its code is as follows:
<h1>Settings</h1>
<%= form_tag admin_settings_path, method: "put" do %>
<p>
<label>Site Title:</label>
<%= text_field_tag "settings[site_title]" %>
</p>
<p>
<label>Site Description:</label>
<%= text_field_tag "settings[site_desc]" %>
</p>
<p>
<%= submit_tag "Save settings" %>
</p>
<% end %>
Now, I'm able to save/update these fields data in relevant model and I can see the data through command Setting.all in rails console. But the issue is, after saving the record via form when I reload the settings index page the form is blank and it is not showing previously saved values in the fields.
What I'm doing wrong here?
You can do what has been mentioned in the previous answer i.e. using a form_for. However, this can also be accomplished by creating a Hash in both the controller actions that creates and processes this form.
In the action that creates this form, the values in the hash could be initialized to blanks/zeros depending upon the input tag and in the action that processes this form, the values in the hash could be assigned to the values obtained from the posted params[].
I ran into the similar issue with form_tag and I used the following code in my index action i.e. the action that renders the form initially:
#search = {name: "", ranking_group: 0}
Whereas, in the search action, I used the following code to fill up this hash:
#search = {name: params[:name], ranking_group: params[:ranking_group]}
Finally, in the view, I used the appropriate default value options with the input tags as below:
<%= text_field_tag :name, #search[:name] %>
<%= select_tag :ranking_group, options_for_select(AmenityEntities::Amenity.ranking_group_options, #search[:ranking_group]), include_blank: true %>
Hope this helps.
I think you need to use form_for(#variable) instead of just a form_tag because you need to persiste the object after save.
form_for works with resources, take a look here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

Ror find record in db and show it to user

This is my first ror app.
I have main page: home.html.erb
I have form there.
<%= form_for(#lead ,:html => {:class => 'check_form'}) do |f| %>
<%= f.text_field :phone, placeholder: 'phone' %>
<%= f.submit "Check car status", class: "btn btn-large btn-primary" %>
<% end %>
Backstory: a customer(I call him Lead can input his phone number and check status of his car which is being repaired now.)
Right now this view home.html.erbis served by static_pages_controller
class StaticPagesController < ApplicationController
def home
#lead = Lead.new()
end
def help
end
def about
end
def contact
end
end
I have also LeadsController
class LeadsController < ApplicationController
*some code*
def create
#lead = Lead.new(lead_params)
if #lead.save
#sign_in #lead
flash[:success] = "Request successfully created!"
redirect_to #lead
else
render 'new'
end
end
* some code
end
What I want to do when user inputs his phone number to find lead in database with the same phone number and show repair status to user.
So back to my problem:
I know how to find lead by phone like this Lead.find(params[:id])
But where to write this code? I need to find lead by phone and then print it to screen. How can I do this?
What I want to do when user inputs his phone number to find lead in
database with the same phone number and show repair status to user.
Currently your form serves the wrong purpose. This requires a form with GET request. I'll be doing it by declaring a custom route like below
get :check_lead_car_status, to: 'static_pages#check_lead_car_status', as: 'check_lead_car_status'
And in the static_pages#check_lead_car_status
def check_lead_car_status
#lead = Lead.find_by(phone: params[:phone]
end
And modify the existing form like below
<%= form_tag check_lead_car_status_path, :method => :get do %>
<%= text_field_tag :phone, placeholder: 'phone' %>
<%= submit_tag "Check car status", class: "btn btn-large btn-primary" %>
<% end %>
And a page check_lead_car_status.html.erb with the below code
The Status of the Car is: <%= #lead.status %>
youre redirecting to #lead which means should be the show path in the lead controller. which means you need to put that logic in a method called show in your Lead controller
then in your view (views/leads/show.html.erb) you can access that variable
edit:
if all youre trying to do is query by a different parameter, then you should look into the active record query interface. specifically section 1.1.5
Lead.find_by(phone: params[:phone])

active admin collection_select and passing to controller override create method

I have list dropdown list in my activeadmin that populates the recipe and menu. I'm trying to override the create method but it is not working
<%= semantic_form_for [:admin, #menu_recipe] do |f| %>
<p>
<%= f.collection_select :recipe_id,
Recipe.all,:id,:name,:prompt => true%>
</p>
<p>
<%= f.collection_select :menu_id,
Menu.all,:id,:name,:prompt => true%>
</p>
<%= f.buttons :commit %>
<%end%>
Whenever I try to catch the and create or group it, it returns with a Couldn't find Recipe without an ID error
my active admin controller which i override is
ActiveAdmin.register MenuRecipe do
menu :parent => "Manage Package"
form :partial => "menu_recipe"
controller do
def new
new! do |format|
#menu_recipe = MenuRecipe.new
end
end
def create
create! do |format|
recipe = Recipe.find(params[:recipe_id])
menu = Menu.find(params[:menu_id])
#menu_recipe = #menu.add_recipe(menu.id)
if #menu_recipe.save
redirect_to {admin_menu_recipe_url}
end
end
end
end
end
im i doing it right? if anything is needed please just ask thanks in advance
My guess is it's how you are getting the recipe_id. I would maybe debug the params and see what the actual values are.
You may need to do something like this:
params[:menu_recipe][recipe_id]

Resources