How to use/customize the mail_form template? - ruby-on-rails

does anybody know how to use the mail_form template?
<h4 style="text-decoration:underline"><%= message.subject %></h4>
<% #resource.mail_form_attributes.each do |attribute, value|
next if value.blank? %>
<p><b><%= #resource.class.human_attribute_name(attribute) %>:</b>
<%= case value
when /\n/
raw(simple_format(h(value)))
when Time, DateTime, Date
I18n.l(value)
else
value
end
%></p>
<% end %>
<% unless #resource.class.mail_appendable.blank? %>
<br /><h4 style="text-decoration:underline"><%= I18n.t :title, :scope => [ :mail_form, :request ], :default => 'Request information' %></h4>
<% #resource.class.mail_appendable.each do |attribute|
value = #resource.request.send(attribute)
value = if value.is_a?(Hash) && !value.empty?
list = value.to_a.map{ |k,v| content_tag(:li, h("#{k}: #{v.inspect}")) }.join("\n")
content_tag(:ul, raw(list), :style => "list-style:none;")
elsif value.is_a?(String)
value
else
value.inspect
end
%>
<p><b><%= I18n.t attribute, :scope => [ :mail_form, :request ], :default => attribute.to_s.humanize %>:</b>
<%= value.include?("\n") ? simple_format(value) : value %></p>
<% end %>
<br />
<% end %>
For example,
#resource.class.human_attribute_name(attribute)
what this code mean?
I can't find it in the documentation it seems the author got lazy. Have any idea?

Related

Rails wrong number of arguments (0 for 1..3) in custom FormBuiler

I am writing a custom FormBuilder in Rails and I get the above error at "around line 14" (<%= f.text_field :name, autofocus: true %>) of the view.
My FormBuilder:
class FoundationFormBuilder < ActionView::Helpers::FormBuilder
delegate :content_tag, to: :#template
delegate :label_tag, to: :#template
def text_field(method, options = {})
options[:label] ||= "#{method.to_s}".humanize
options[:class] ||= ""
field_errors = object.errors[method].join(', ') unless object.errors[method].blank?
error_class = "error" if field_errors
error_class ||= ""
label_tag("#{#object_name}[#{method}]", "#{options[:label]}", class: error_class) do
label << #template.send(text_field_tag("#{#object_name}[#{method}]", nil, class: "error_class #{options[:class]}"))
# label << (content_tag(:small, field_errors.humanize, class: error_class)) if field_errors
label.html_safe
end
end
end
In my view:
<%= form_for(#message, url: contact_us_path, builder: FoundationFormBuilder) do |f| %>
<!--<%= f.label :name %>-->
<%= f.text_field :name, autofocus: true %>
<!--<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :comment %>
<%= f.text_area :comment, rows: 10 %>
<%= f.submit "Send", class: "button round right" %>-->
<% end %>
Here is the application trace:
app/helpers/foundation_form_builder.rb:13:in `block in text_field'
app/helpers/foundation_form_builder.rb:3:in `label_tag'
app/helpers/foundation_form_builder.rb:12:in `text_field'
app/views/contact_us/new.html.erb:14:in `block in _app_views_contact_us_new_html_erb___968573049544088412_70132699754860'
app/views/contact_us/new.html.erb:12:in `_app_views_contact_us_new_html_erb___968573049544088412_70132699754860'
As far as I can tell I am passing the arguments to the label_tag since I presume this is what is causing the error. What am I actually doing wrong?
Update:
I think it has to do with the method beign passed as text_field to a label, but I'm not sure. Still scratching my head.
The issue was trying to append to label when I had not initialised it previously.
What I wanted to achieve was the following:
<form>
<div class="row">
<div class="large-6 columns">
<label class="error">Error
<input type="text" class="error" />
</label>
<small class="error">Invalid entry</small>
</div>
<div class="large-6 columns error">
<label>Another Error
<input type="text" />
</label>
<small class="error">Invalid entry</small>
</div>
</div>
<textarea class="error" placeholder="Message..."></textarea>
<small class="error">Invalid entry</small>
</form>
As seen here Zurb - Foundation 5 Forms
Which has been done as follows:
FormBuilder:
class FoundationFormBuilder < ActionView::Helpers::FormBuilder
delegate :content_tag, to: :#template
delegate :label_tag, to: :#template
def text_field(method, options = {})
options[:label] ||= "#{method.to_s}".humanize
options[:class] ||= ""
field_errors = object.errors[method].join(', ') unless object.errors[method].blank?
options[:class] << "error" if field_errors
options = objectify_options(options)
options.delete(:object)
label = lambda do
label_tag("#{#object_name}[#{method}]", "#{options[:label]}", class: "#{'error' if field_errors}") do
label = "#{options[:label]}"
label << #template.send('text_field_tag', "#{#object_name}[#{method}]", nil, options)
label.html_safe
end
end
error_messages = lambda do
content_tag(:small, field_errors.humanize, class: "error") if field_errors
end
"#{label.call} #{error_messages.call}".html_safe
end
def text_area(method, options = {})
options[:label] ||= "#{method.to_s}".humanize
options[:class] ||= ""
field_errors = object.errors[method].join(', ') unless object.errors[method].blank?
options[:class] << "error" if field_errors
options = objectify_options(options)
options.delete(:object)
label = lambda do
label_tag("#{#object_name}[#{method}]", "#{options[:label]}", class: "#{'error' if field_errors}") do
label = "#{options[:label]}"
label << #template.send('text_area_tag', "#{#object_name}[#{method}]", nil, options)
label.html_safe
end
end
error_messages = lambda do
content_tag(:small, field_errors.humanize, class: "error") if field_errors
end
"#{label.call} #{error_messages.call}".html_safe
end
end
View:
<%= form_for(#message, url: contact_us_path, builder: FoundationFormBuilder) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :email %>
<%= f.text_area :comment, rows: 10 %>
<%= f.submit "Send", class: "button round right" %>
<% end %>
It has achieved the result, but is this a safe way to achieve what I wanted?

getting checkbox value in ruby on rails

I have a checkbox below in a view page:
<table>
<tr>
<td>
<% #user_profession.each do |p| %>
<% if !p.Designation.blank? and p.Private? == "1" %>
<%= check_box(:ChkBx_Profession, {:id => "ChkBx_Profession",:value => "Profession"},true) %>
<%= label(:lb_Profession, "Profession") %>
<% else %>
<%= check_box(:ChkBx_Profession,{:id => "ChkBx_Profession",:value => "Profession"}) %>
<%= label(:lb_Profession, "Profession") %>
<% end %>
<% end %>
</td>
</tr>
</table>
Below is my controller page
if params[:ChkBx_Profession] == "1"
#blah = params[:ChkBx_Profession]
#publicprofession = params[:ChkBx_Profession]
Profession.delete_all(:UserID => current_user.id)
if !params[:tf_designation].blank?
#desig = params[:tf_designation]
#comp = params[:tf_company]
#fromdesigcom = params[:tf_fromdesignation]
#todesigcom = params[:tf_todesignation]
#public_profession = #publicprofession
#Profession = Profession.new( :UserID => current_user.id, :Designation => #desig, :Company => #comp, :Job_From => #fromdesigcom, :Job_To => #todesigcom, :Private? => #publicprofession )
#Profession.save
end
end
and I want to get the checkbox value means if checkbox is checked it gets me 1 and if checkbox is unchecked it gets me 0 but its get like this {"{:id=>\"ChkBx_Profession\", :value=>\"Profession\"}"=>"1"}. Kindly help me waiting for your reply.
Thanks
The second attribute on an check_box is the :value attribute. Try putting empty double quotes between the chec_box name AND the options:
<%= check_box(:YourCheckName, "",{Your Options}) %>

Validation in form?

I am trying to do validation but didnot find the right way while uploading the excel
Code for view
<%= form_for :dump, :url=> import_csv_index_path, :html => { :multipart => true } do |f| %>
<% if (-----).errors.any? %>
<div id="error_explanation">
<%= pluralize((----).errors.count, "error") %> prohibited this link from being saved:
<% (---).errors.full_messages.each do |msg| %>
<li><%= msg %></li>
</div>
<% end %>
<%= f.label :'Select an Excel File:' %>
<%= f.file_field :file %>
<i href="#" id="blob_1" class="icon-info-sign" rel="popover" style="margin-top: 300px"></i><br/>
<%= submit_tag 'Submit' ,:id => 'submit',:class =>"btn btn-primary"%><br/><br/>
<% end -%>
Code for model:
class Person < ActiveRecord::Base
attr_accessible :date, :email, :name, :avatar ,:template_id
validates_presence_of :email,:message => 'Email is compulsory'
end
What do i write at place of (-----)
Thank you
I have done with the other approach so discuss here,
Code for controller:
def import
#error = []
#error = Person.import(params[:dump][:file])
redirect_to people_path, notice: "Employees imported.",:flash => { :error => "Employees( Email : invalid/blank) are not saved : #{#error.join(" , ")}" }
end
In model:
def self.import(file)
spreadsheet = open_spreadsheet(file)
#err = []
#alt = []
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
#person = Person.find_by_id(row["id"]) ||Person.new
#person.name = row["Name"].to_s
#person.date = row["Date"]
#person.email = row["Email"]
if #person.save
else
#err << {:name => row["Name"].to_s,:error => #person.errors.messages}
end
end
#err.each do |t|
#alt.push(t[:name])
end
return #alt
end
and call that as flash message...and working fine now.
Thanks
I think somewhere in your controller you have to call .validate on a new instance of your Person model with your form's data. You can save that model in an instance variable that you can put in place of the (-----).

Rails duplicate loop - Hash and array loop

In my view I have:
<% #results.each_pair do |country_code, available| %>
<% #prices.each do |cc,domain| %>
<% klass = available.registered? ? "pinfo" : "info" %>
<span class="<%= klass %>"></span>
<%= #domain + country_code %> <%= domain.send(cc) %>$<br />
<% end %>
<% end %>
And the output is:
asdsaddk 8$
asdsaddk 1$
asdsadcom 8$
asdsadcom 1$
My controller:
def domain
country_codes = %w[ dk com ]
#domain = "asdsad"
#results = { }
#prices = { }
country_codes.each do |cc|
#results[cc] = Whois.whois("#{#domain}.#{cc}")
#prices[cc.to_sym] = Domain.order(cc).first
end
render :layout => false
end
How do I create a normal loop like where the output is not duplicate like:
asdsaddk 8$
asdsadcom 1$
Replace:
<% #results.each_pair do |country_code, available| %>
<% #prices.each do |cc,domain| %>
<%= #domain + country_code %> <%= domain.send(cc) %>$<br />
<% end %>
<% end %>
With:
<% #prices.each do |cc,domain| %>
<%= #domain + cc.to_s %> <%= domain.send(cc) %>$<br />
<% end %>
Indeed, you don't use the available variable from #results.
Sidenote: once again, you don't have any array here, only Hashes.
Reorganization needed:
def domain
country_codes = %w[ dk com ]
#domain = "asdsad"
#output = { }
country_codes.each do |cc|
#output[cc.to_sym] = { :whois => Whois.whois("#{#domain}.#{cc}"),
:domain => Domain.order(cc).first }
end
render :layout => false
end
In your view:
<% #output.each do |cc, hash| %>
<span class="<%= hash[:whois].registered? ? "pinfo" : "info" %>"></span>
<%= #domain + key.to_s %> <%= hash[:domain].send(cc) %>$<br />
<% end %>

Rails custom validations with multi-model forms

I'm having problems with my rails custom validations.
def validates_hsp_program(*attr_names)
options = attr_names.extract_options!
regex = '^('
err = ''
$CetConfig.program.each do |key, val|
regex << val.to_s << '|'
err << $CetConfig.program_prefix + " " + val.to_s + ", "
end
regex.chomp!('|')
regex << ')$'
regex = Regexp.new(regex)
validates_each attr_names do | record, attr_name, value |
exit 1
unless value.nil? or value =~ regex
record.errors.add(attr_name, 'must be one of ' + err.chomp(", "));
end
end
end
The problem is that for debugging purposes I added exit 1 as I wasn't getting the error message for invalid date for that field. However, it never exits. This is the same thing I do in all my other custom validators. The only difference I can see is that this one is the second model of a multi-model form and all the others are on the first model... What am I doing wrong?
My Model
class ProfileProgram < ActiveRecord::Base
set_table_name "profile_program"
set_primary_key "STUDENT_ID"
belongs_to :profile_core, :primary_key => "STUDENT_ID", :foreign_key => "STUDENT_ID"
validates_presence_of :program
validates_hsp_program :program
end
Action from my controller
def create
#pc = ProfileCore.new(params[:profile_core])
#pp = ProfileProgram.new(params[:profile_program])
#pc.student_type = $CetConfig.student_type.application
#pc.AGENT_ID = current_agents_staff.AGENT_ID
year = #pc.contract.to_s
case #pp.program
when 10 then
sd = year + '-09-01'
ed = year + '-06-30'
when 51 then
sd = year + '-08-15'
ed = year + '-06-30'
when 52 then
sd = year + '-01-15'
ed = year + '-06-30'
when 12 then
sd = year + '-01-15'
ed = year + '-01-14'
else
sd = nil
ed = nil
end
#pc.start_date = Date.parse(sd) unless sd.nil?
#pc.end_date = Date.parse(ed) unless ed.nil?
#pc.program_status = $CetConfig.student_status.apply
if #pc.valid? and #pp.valid?
ProfileCore.transaction do
#pc.save!
#pp.save!
end
redirect_to(students_path(#pc.STUDENT_ID))
else
render :action => 'new'
end
end
My view (element_block is a helper that just stuffs the label and field into the right tags for the dl)
<% form_for :profile_core, #pc, :url => { :controller => 'core', :action => 'create'} do |f| %>
<%= error_messages_for :object => [ #pc, #pp ] %>
<dl>
<%= element_block f.label(:contract, 'Contract Year'), f.contract_year_select(:contract) %>
<% fields_for :profile_program do |pp| %>
<%= element_block pp.label(:program, 'Program'), pp.hsp_program_select(:program) %>
<% end %>
<%= element_block f.label(:passport_number, 'Passport Number'), f.text_field(:passport_number) %>
<%= element_block f.label(:passport_country, "Country that issued the student's passport"), f.countries_select(:passport_country) %>
<%= element_block f.label(:passport_expires, 'Passport Expiration Date'), f.text_field(:passport_expires, :class => 'datepicker') %>
<%= element_block f.label(:last_name, 'Last Name (as on passport)'), f.text_field(:last_name) %>
<%= element_block f.label(:first_name, 'First Name (as on passport)'), f.text_field(:first_name) %>
<%= element_block f.label(:middle_name, 'Middle Name (as on passport)'), f.text_field(:middle_name) %>
<%= element_block f.label(:other_names, 'Other Names'), f.text_field(:other_names) %>
<%= element_block f.label(:residence_street_address, 'Street Address'), f.text_field(:residence_street_address) %>
<%= element_block f.label(:residence_city, 'City'), f.text_field(:residence_city) %>
<%= element_block f.label(:residence_province, 'Province'), f.text_field(:residence_province) %>
<%= element_block f.label(:residence, 'Country'), f.text_field(:residence) %>
<%= element_block f.label(:residence_postal_code, 'Postal Code'), f.text_field(:residence_postal_code) %>
<%= element_block f.label(:birthdate, 'Date of Birth'), f.text_field(:birthdate, :class => 'datepicker', :id => "student_birth_date") %>
<%= element_block f.label(:citizenship, 'Country of Citizenship'), f.countries_select(:citizenship) %>
<%= element_block f.label(:birth_city, 'Birth City'), f.text_field(:birth_city) %>
<%= element_block f.label(:nationality, 'Nationality'), f.countries_select(:nationality) %>
<%= element_block f.label(:gender, 'Gender'), f.gender_select(:gender) %>
<%= element_block f.label(:email, 'Email'), f.text_field(:email) %>
<%= element_block f.label(:desires_esl, 'Does the student wish to participate in CLEP?'), f.bool_yes_no_select(:desires_esl) %>
<%= element_block f.label(:may_pay_tuiton, 'Willing to pay tuition'), f.yes_no_select(:may_pay_tuition) %>
</dl>
<div class="submit"><%= submit_tag("Proceed to Step Two") %></div>
<% end %>
This is how I ended up taking care of it with accepts_nested_attributes_for
Primary Model. (Irrelevant code replaced with ellipses)
class ProfileCore < ActiveRecord::Base
set_table_name "profile_core"
set_primary_key "STUDENT_ID"
belongs_to :agents_profile, :primary_key => "AGENT_ID", :foreign_key => "AGENT_ID"
has_one :profile_program, :primary_key => "STUDENT_ID", :foreign_key => "STUDENT_ID"
accepts_nested_attributes_for :profile_program
...
end
Secondary Model
class ProfileProgram < ActiveRecord::Base
set_table_name "profile_program"
set_primary_key "STUDENT_ID"
belongs_to :profile_core, :primary_key => "STUDENT_ID", :foreign_key => "STUDENT_ID"
validates_presence_of :program
validates_hsp_program :program
end
New action in the controller. (Create was irrelevant)
def new
#pc = ProfileCore.new
#pp = #pc.build_profile_program
end
View
<% form_for #pc, :url => { :controller => 'core', :action => 'create'} do |f| %>
<%= f.error_messages %>
<dl>
<%= element_block f.label(:contract, 'Contract Year'), f.contract_year_select(:contract) %>
<% f.fields_for :profile_program do |pp| %>
<%= element_block pp.label(:program, 'Program'), pp.hsp_program_select(:program) %>
<% end %>
<%= element_block f.label(:passport_number, 'Passport Number'), f.text_field(:passport_number) %>
...
<% end %>
It's not correct custom validation implementation, try something like that:
http://marklunds.com/articles/one/312
or http://chrisblunt.com/blog/2009/04/18/rails-writing-dry-custom-validators/

Resources