erb file syntax - sql

a = Array.wrap(params[:a]).join(', ')
<% unless a.blank? %>
<%= a%>,
<% end %>
b = Array.wrap(params[:where]).join(' AND ')
<% unless params[:dedup] %>
table_name
WHERE <%= input_data_filter %>
<% unless b.blank? %>
AND <%= b %>
<% end %>
AND c - d <= <%= f%>
<% else %>
This is the part of hql.erb file trying to write a query from it, can I transform the unless part of erb file into sql function

In an .erb template, everything that is not contained in <% %> is going to be evaluated as text. Fixing up what you have, you may want to try something like:
<% a = Array.wrap(params[:a]).join(', ') %>
<% unless a.blank? %>
<%= a%>
<% end %>
<% b = Array.wrap(params[:where]).join(' AND ') %>
<% unless params[:dedup] %>
<%= table_name %>
WHERE <%= input_data_filter %>
<% unless b.blank? %>
AND <%= b %>
<% end %>
AND c - d <= <%= f%>
<% else %>

Related

Rails 3 - Ransack - check_box_tag

Listing Model - belongs_to :area
Area Model - has_many :listings
I'm trying to implement a search using Ransack with check boxes; where user checks selected areas, search returns all the listings of the areas selected.
<%= search_form_for #search do |f| %>
<% areas = Area.all %>
<% areas.each do |area| %>
<%= check_box_tag('q[area_id_eq][]', area.id) %>
<%= area.location%>
<% end%>
<%= f.submit "SEARCH" %>
<% end %>
Console output:
Parameters: {"utf8"=>"✓", "q"=>{"area_id_eq"=>["1", "2"]}, "commit"=>"SEARCH"}
Completed 500 Internal Server Error in 4ms
NoMethodError - undefined method `to_i' for ["1", "2"]:Array:
Just not sure how to implement it to accept multiple check box values.
Instead of using "area_id_eq", use "area_id_any". You'll also want to check to make sure that your parameters are selected:
<%= search_form_for #search do |f| %>
<% areas = Area.all %>
<% areas.each do |area| %>
<%= check_box_tag('q[area_id_eq_any][]', area.id, (params[:q][area_id_eq_any].include? area.id.to_s) ? true : false ) %>
<%= area.location%>
<% end%>
<%= f.submit "SEARCH" %>
<% end %>

How to check if an ActiveRecord table entry is empty

I am not sure if the title of this question uses proper jargon, but hopefully this description will help. If you need more information, please let me know.
I am taking Chinese text from a form and splitting it into a 2d array of sentences and words. I then want to define all the words using dictionary entries in my database. Some of the words aren't in the database, so I want to check for that. What I am trying isn't working.
Here is my current code:
<% #lesson.parsed_content.each_with_index do |sentence, si| %> #iterate 1st dimension
<% sentence.each_with_index do |word,wi| %> #iterate 2nd dimension
<% sentence = sentence.to_s %>
<div class="word blt" id="<%= wi %>">
<div class="definition blt">
<% definition = DictionaryEntry.where(:simplified => word) %> #search by simplified chinese
<% definition.find_each do |w| %>
<% if w.definition == nil %> # PROBLEM: this never returns true.
<%= word %>
<% else %>
<%= w.definition %>
<% end %>
<% end %>
</div>
<div class='chinese blt'> <%= word %></div>
</div>
<% end %>
<% end %>
How can I change <% if w.definition == nil %> to return true if there is no definition in my database?
This is a shot in the dark but first I would switch your code around when you are converting the variable sentence to a string and looping through it. (unless you have a reason for it being that way)
<% sentence = sentence.to_s %>
<% sentence.each_with_index do |word,wi| %> #iterate 2nd dimension
Second, depending on how your data was put inside the database it might be an empty string instead of nil. So I would change the condition from
<% if w.definition == nil %> # PROBLEM: this never returns true.
to
<% if w.definition.blank? %> # Checks to see if definition is blank
Blank will check if its false, empty, or a whitespace string.
Finally, indentation is helpful especially when running loops and conditionals. It's easier on the eyes and helps you understand what's going on.
<% #lesson.parsed_content.each_with_index do |sentence, si| %>
<% sentence = sentence.to_s %>
<% sentence.each_with_index do |word,wi| %>
<div class="word blt" id="<%= wi %>">
<div class="definition blt">
<% definition = DictionaryEntry.where(:simplified => word) %>
<% if definition.empty? %>
<% word %>
<% else %>
<% definition.find_each do |w| %>
<%= w.definition %>
<% end %>
<% end %>
</div>
<div class='chinese blt'> <%= word %></div>
</div>
<% end %>
<% end %>
Let me know the results.

Rails: dynamically naming instance variables

Just wondering how to dynamically name (say, in a loop) a series of instance variables. Something like this:
<% #current_issue.articles.each_with_index do |a, i| %>
<% i += 1 %>
<%= f.collection_select("article#{i}", #articles_hash1, :first, :last) %>
<% #articles1.each do |r| %>
<%= link_to(image_tag(r.image.url(:large)), r.image.url(:large), :id => 'article'+i.to_s+'_thumb'+r.id.to_s) %>
<% end %>
<% end %>
Where instead of #articles_hash1 it'd be #articles_hash[i]. I'm just not sure how to achieve that.
Cheers!
<% #current_issue.articles.each_with_index do |a, i| %>
<%= f.collection_select("article#{i}", #articles_hash[i], :first, :last) %>
<% #articles_hash[i].each do |r| %>
<%= link_to(image_tag(r.image.url(:large)), r.image.url(:large), :id => 'article'+i.to_s+'_thumb'+r.id.to_s) %>
<% end %>
<% end %>
I didn't check for any syntax issues, but this should do.
For anyone struggling with this, do yourself a favour and build an array of the instance variables in question, i.e.:
#articles = (1..3).to_a.map { |i| Article.all_articles(i).reverse }
And then loop through that array, i.e.:
<% #articles.each_with_index do |a, i| %>
<% i += 1 %>
<%= f.collection_select("article#{i}", #articles[i-1], :id, :name) %>
<% end %>

How to select only checked records using check_box_tag?

Guys my check_box_tag looks like as follows
<%= form_tag({:action => 'update_survey_list_status',:projectid=>params[:id], :status=>4}, :id => 'to_be_approved_frm') do %>
<% #publishedlist.each do |b| %>
<%= fields_for "beneficiaryloan[#{b.id}]" do |bloan| %>
<%= bloan.text_field :amount, :class=>'forms_txtbx'%>
<%= bloan.text_field :rate, :class=>'forms_txtbx'%>
<%= bloan.text_field :period, :class=>'forms_txtbx'%>
<% end %>
<%= check_box_tag "benificiary_id[#{b.id}]",b.id,:name => "benificiary_id[]"%>
<% end %>
<%= submit_tag "Approve", :class=>'form_buttons' %>
<% end %>
And in controller, I'm reading all the beneficiary ids like this
params[:beneficiaryloan].each do |key, value|
beneficiary = Beneficiary.find(key) rescue nil
#benefciary_loan=beneficiary.beneficiaryloans.build(value)
#benefciary_loan.beneficiary_id=beneficiary.id
#benefciary_loan.hfi_id=session[:id].to_s
#benefciary_loan.status_id=params[:status]
#benefciary_loan.save if beneficiary
end
What I need is, Inserting all the beneficiary ids to [beneficiaryloans] table which are checked, but in my case it inserting all records even some of them are unchecked.
How to do I select only checked ids?
Try changing your check_box_tag to
<%= check_box_tag "beneficiaryloan[#{b.id}][enabled]", 1, true %>
Then in your controller do the following:
params[:beneficiaryloan].select{|k,v| v.delete(:enabled).to_i > 0 }.each do |k,v|
..
end
Since the enabled attribute has no influence in the model you can just delete it out of the resulting beneficiary_load hashes.

Rails - Display a title only once in an .each block

Noob question here :)
I'm testing a variable, and if it exists, I'd like to display an .each loop with a title.
Of course, the title should be displayed only once. Is there a way to do it? Any best practice?
<%
#twitter_friends.each do |u|
if #user = User.is_a_member?(u.id)
%>
# HERE I'D LIKE TO DISPLAY THE TITLE ONLY AT FIRST ITERATION
<% #user.name %> is your twitter friend, and is a member.
<% end %>
<% end %>
Thanks !
I would normally recommend using each_with_index and checking for a zero index, but seeing as you have a conditional in the loop, you should use a check variable like so:
<% shown_title = false %>
<% #twitter_friends.each do |u| %>
<% if #user = User.is_a_member?(u.id) %>
# HERE I'D LIKE TO DISPLAY THE TITLE ONLY AT FIRST ITERATION
<% unless shown_title %>
<h1>My Title</h1>
<% shown_title = true %>
<% end %>
<% #user.name %> is your twitter friend, and is a member.
<% end %>
<% end %>