How to pass name of form_for's method to partial in rails? - ruby

Good day! Little newbee question:
let's say I want to generate fields of form_for helper of special appearance. Thus to not to repeat complex code to generate many fields of model, I render some partial and pass there parameters. There is a reference to form object amongst them. Question is what pass to render method to call in the partial necessary method of form object? For example I want to generate this time email_field:
<%= form_for #order do |f| %>
<%= render :partial => 'form_field_special', :locals => {:form => f, :type => :email_field, :labelcaption => "SpcName"} %>
<% end %>
and partial itself:
<div class="control-group">
<%= f.label :name, <%= labelcaption %> , :class => "control-label" %>
<div class="controls">
<%= f.type :name %> # ??????
</div>
</div>
thank you guys!

Use ruby power. Object#send method:
<%= form_for #order do |f| %>
<%= render :partial => 'form_field_special', :locals => {..., :field_type => 'email_field'} %>
<% end %>
<%= f.send(field_type, :name) %>

The following method proved as the fastest way to invoke ruby object's function by its name:
m = form.method(name_of_the_method)
m.call(parameters)

Related

How to solve ParameterMissing error using ROR

Please help me to solve the below error.
Error:
ActionController::ParameterMissing in CustmersController#create
param is missing or the value is empty: users
When i am submitting the data,this error is coming.
My code is as follows
views/custmers/new.html.erb
<h1>Enter your data here</h1>
<center>
<%= form_for #users,:url => {:action => 'create'} do |f| %>
<% if #users.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#users.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #users.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="name">Name:</label>
<%= f.text_field :name,placeholder:"Enter your name",:class => "input-field" %>
</p>
<p>
<label for="email">Email:</label>
<%= f.email_field :email,placeholder:"Enter your email",:class => "input-field" %>
</p>
<p>
<label for="phone">Phone no:</label>
<%= f.telephone_field :phoneno,placeholder:"Enter your phone number",:class => "input-field" %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
<%= link_to "BACK",custmers_index_path %>
</center>
controller/custmers_controller.rb
class CustmersController < ApplicationController
def index
end
def new
#users=Custmer.new
end
def show
end
def create
#users=Custmer.new(user_params)
if #users.save
flash[:notice]="You have signed up successpully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="You have not signed up successfully"
flash[:color]="invalid"
render :new
end
end
private
def user_params
params.require(:users).permit(:name,:email,:phoneno)
end
end
model/custmer.rb
class Custmer < ActiveRecord::Base
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name,presence:true,length: { minimum: 5 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :phoneno, presence: true,length: {minimum: 10}
end
I am using rails version-4.2.0 and ruby version-1.9.3.Please help me to resolve this error.
If you look at the stack trace accompanying your error, you could tell definitely where the problem is -- look for the first line in the stack trace that refers to your code (and not library code).
But a fair guess is the require(:users) line in your controller. It looks like you either copy/pasted this code from another controller, or changed the name of your controller after generating it as part of your scaffold.
It should be requires(:custmer) instead, as that is the class of the thing you're submitting.
As a general approach, you should follow the standard Rails practices for naming things, throughout. If you really want to use the misspelled, Custmer class, have at it, but use #custmr inside your controller and views to refer to an instance, not #users.

Formtastic Creating a form without users

I'm creating a web application with formtastic. I installed the gem and wrote my code like this:
<%= semantic_form_for #index do |form| %>
<%= form.inputs do %>
<%= form.input :name %>
<%= form.input :born_on, :start_year => 1997 %>
<%= form.input :description, :as => :text %>
<%= form.input :female, :as => :radio, :label => "Gender", :collection => [["Male", false], ["Female", true]] %>
<% end %>
<%= form.actions do %>
<%= form.action :submit, :as => :button %>
<% end %>
<% end %>
I want the form to appear on the index page which is why I have #index. For some reason I can't do #index. How would I reference the top line so that it renders a form on the index page? Currently my index page has nothing in it, but it is defined in the controller
form_for helper expects some object that responds to fields You refer inside Your form. Here is an example of using semantic_form_for with plain Ruby object: http://affy.blogspot.com/2010/02/using-formtasic-without-activerecord.html.
Also the object You specify for form doesn't effect which page is being rendered. Are You sure You are not mixing up something? Maybe if You share a bit more of Your controller code we might help You better.

Get value of a hidden field tag Ruby on Rails

I am lost, I do not know what I'm doing wrong! I have 4 radio buttons and a hidden field (value = "1"). When you click on the second radiobutton, the value of the hidden field changes to 2 and so on. This works fine with a js function.
Different divs will be showed when a different radiobutton is selected. Now, when I'm trying to get the value of the hidden field in my controller it always returns nil.
Here's the code:
view:
(radiobuttons, hiddenfield and one div)
<div>
<%= form_tag patients_path do %>
<%= radio_button_tag 'searchRBN', 'patient', true, :onchange => "checkRadioButton()" %>
<%= label_tag :byPatient_patient, "Patient" %>
<%= radio_button_tag 'searchRBN', 'staff', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byStaff_staff, "Staff" %>
<%= radio_button_tag 'searchRBN', 'ocmw', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byOcmw_ocmw, "OCMW" %>
<%= radio_button_tag 'searchRBN', 'mutuality', false, :onchange => "checkRadioButton()" %>
<%= label_tag :byMutuality_mutuality, "Mutuality" %>
<%= hidden_field_tag :hidden_one, "1" %>
<% end %>
</div>
<div id="searchByPatient">
<%= form_tag patients_path, :method => 'get' do %>
<p>
<%= text_field_tag :search1, params[:search1] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
</div>
controller:
def index
#staff_all = Staff.all
#ocmw_all = Ocmw.all
#mutuality_all = Mutuality.all
debugger
if params[:hidden_one] == '1'
#patients = Patient.searchByName(params[:search1])
elsif params[:hidden_one] == '2'
#patients = Patient.searchByStaff(params[:search2])
else
#patients = Patient.all
end
end
It's because you have two forms. When you submit the second form it won't send the fields of the first form. If you put everything in one form it will work as expected.
Use only single form:
Also as a workaround use two submit tag in a single form:
differentiate both the action with params[:action]
For Example:
<%= form_for :attachment_metadata, :url=>{:action=>'delete_files'}, :html=>{:onsubmit=> "return confirm('Are you sure, you want to delete selected files?');",:multipart => true} do |f| %>
<table>
..........Some stuff here..........
</table>
<%= submit_tag 'Reprocess', :class =>'button' %>
<%= submit_tag 'Remove', :class =>'button' %>
<% end %>
params[:commit] can differentiate the actions of two submit tags.
#action = params[:commit]
it gives #action value as "Reprocess" if your click the Reprocess button and gives "Remove" value if you click the Remove button,
Then you will get your values.

Paperclip multiple upload & save extra field

Im stuck uploading multiple photos to my model when adding an extra field to the photo model. In the code i hard code "1" value to the hidden_field, but i will change it eventually. The paperclip gem raises a rollback and won't insert the photos in the post. If i erase the "hidden_field" line it will success. Any ideas on how to add extra field to the upload in the view?
<%= form_for #campaign_point_of_sale, :html => {:multipart => true }, :url => "/pos/#{#point_of_sale.id}/post/#{#campaign.id}", :method => :post do |f| %>
<%= f.hidden_field :id %>
<label>Add photo <br />
<%= f.fields_for :campaign_result_point_of_sale_photos do |builder| %>
<% if builder.object.new_record? %>
<%= builder.hidden_field :is_mount_photo, :value => "1" %>
<%= builder.file_field :photo %>
<% end %>
<% end %>
<%= f.submit(:value => "Save") %>
Got it!
Just needed to delete the whole builder with both hidden_field and file_field, so the server would not try to insert a picture without an image file (just with a hidden_field value)
This can be achivied by surrounding both inputs with a div and deleting it (with jquery) at form submit if the file_field value was empty. Pretty cheap but works!

Getting undefined method `klass' for nil:nilclass - Railscast #197

Hi all I followed Ryan Bates' railscasts on nested models and form, but I am getting getting undefined method `klass' for nil:nilclass. I am pretty sure it is due to the the link_to_add_fields since everything was working prior. Below is my error and other relevant code and I'm using Rails 3.1. I did a lot of googling and did not find any to solve my problem, so if you guys could help me out I would really appreciated it. Thanks for your help.
_form.html.erb
<%= form_for(#organization) do |f| %>
<% if #organization.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#organization.errors.count, "error") %> prohibited this organization from being saved:</h2>
<ul>
<% #organization.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div id="restaurant_field" class="field">
<%= f.fields_for :restaurants do |builder| %>
<%= render 'organizations/partials/restaurant_fields', :f => builder %>
<% end %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
_restaurant_fields.html.erb
<p class="fields">
<%= f.label :name, "Restaurant Name" %><br />
<%= f.text_field :name %>
<%= link_to_remove_fields "Remove", f %>
application_helper.rb
module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
end
application.js
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
I found that the link_to_add_fields helper won't work if the associated model is describe by a has_one. The has_one means the association does not get the klass object.
You can determine this is your problem by changing your relationship to has_many :object + s (your object name with an s) and passing your object in plural to link_to_add_fields.
You have done the same thing as this person here
Edit: (error on my part)
I am assuming you have an link_to_add_fields below this line
<%= link_to_remove_fields "Remove", f %>
as it seems that the _restaurant_fields.html.erb partial is incomplete. (no closing tag)
</p>
Remove the link_to_add_fields outside of the f.fields_for
That should solve the klass error.

Resources