Rails duplicate loop - Hash and array loop - ruby-on-rails

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 %>

Related

Aggregation on Many to many relations activerecord

I want to make ES aggregation on many to many activerecord model on rails but no way
My model :
class Foo < ApplicationRecord
searchkick
def search_data
{
bar: bar
}
end
has_many :bars
end
I have tried many solution but always get
{"active"=>{"doc_count_error_upper_bound"=>0, "sum_other_doc_count"=>0, "buckets"=>[]}}
The answer is add this :
def search_data
Attributes.merge(
bar_names: bar.map(&:name)
)
end
Here more about how to work with associated models, here is:
Item.rb (model):
# Relations
belongs_to :brand
## many-to-many relations between Items and Textures
has_many :item_attribute_for_textures
has_many :textures, through: :item_attribute_for_textures, :class_name => 'ItemAttribute::Texture'
# Searchkick
searchkick
def search_data
{
full_item_title: full_item_title,
brand: brand.try(:title),
texture: textures.map(&:title)
}
end
ItemController.rb:
def index
args = {}
args[:brand] = params[:brand] if params[:brand].present?
args[:texture] = params[:texture] if params[:texture].present?
query = params[:busca].presence || "*"
#items = Item.search query, where: args,
aggs: {
full_item_title: {},
brand: {},
texture: {}
}
end
and view index.html.erb:
<div class="row">
<div class="col-sm-2" style="font-size: 0.75rem">
<h5>Brands</h5>
<div>
<% #items.aggs["brand"]["buckets"].sort_by{ |b| b["key"] }.each do |bucket| %>
<div>
<% if params[:brand] == bucket["key"].to_s %>
<strong><%= bucket["key"] %></strong>
<% else %>
<%= link_to bucket["key"], request.params.merge(brand: bucket["key"]) %>
<% end %>
(<%= bucket["doc_count"] %>)
</div>
<% end %>
</div>
<hr>
<h5>Texture</h5>
<div>
<% #items.aggs["texture"]["buckets"].sort_by{ |b| b["key"] }.each do |bucket| %>
<div>
<% if params[:texture] == bucket["key"].to_s %>
<strong><%= bucket["key"] %></strong>
<% else %>
<%= link_to bucket["key"], request.params.merge(texture: bucket["key"]) %>
<% end %>
(<%= bucket["doc_count"] %>)
</div>
<% end %>
</div>
<hr>
</div>
</div>

How to use/customize the mail_form template?

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?

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 (-----).

block method output is generating twice

I write a block method to print a list
def column (&block)
if block_given?
content_tag(:li, capture(self, &block))
else
content_tag(:li, "")
end
end
and using it as
<%= data_list_for #leads, [" :10", "Age:30", "Contact:140", "Phone:140", "Email:180", "Company:100", ""] do |l| %>
<%= l.column { |c| link_to " ".html_safe, "leads/details/#{c.object.id}", :class=>:plus, :remote=>true } %>
<%= l.column { |c| c.object.age } %>
<%= l.column { |c| c.object.contact.complete_name } %>
<%= l.column { |c| c.object.contact.phones.blank? ? "-" : c.object.contact.phones.first.phone_number } %>
<%= l.column { |c| c.object.contact.emails.blank? ? "-" : c.object.contact.emails.first.email } %>
<%= l.column { |c| c.object.company.title } %>
<%= l.column do |c| %>
<%= options_menu do |m| %>
<%= m.item link_to 'Show', lead_path(c.object) %>
<%= m.item link_to 'Edit', edit_lead_path(c.object) %>
<%= m.item link_to 'New Note', "leads/#{c.object.id}/notes/new", :class=>"display-newxdoc", :id=>c.object.id %>
<%= m.item link_to 'Create Opportunity', new_lead_opportunity_path(c.object) %>
<% end %>
<% end %>
<% end %>
Every thing is working fine. But the only problem is that options_menu is generating twice. Means two option_menus are there. I traced out one menu is from l.column command because it has proper formating of column, other is generating by its on block in the view, How can i stop it for doing twice?
Remove = from the line
<%= options_menu do |m| %>
I wouldn't use capture if the block is direct (not a "view block"):
content_tag(:li, block.call(self))
The solution is now posted in the discussion.

Resources