Rails: dynamically naming instance variables - ruby-on-rails-3

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

Related

erb file syntax

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

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

How to access attributes in a partial of a nested rails form?

I want to use the boolean attribute is_white from my inner_object to switch between html code in the the partial _inner_object_form_fields. This is my attempt.
<%= form_for #outer_object do |f| %>
<%= f.fields_for :inner_object do |builder| %>
<%= render :partial => "inner_object_form_fields", :locals => { :f => builder } %>
<% end %>
<% end %>
This is my attempt of the partial _inner_object_form_fields.
<% if f.is_white == true %>
<%= f.label(:name, "White") %>
<% else %>
<%= f.label(:name, "Black") %>
<% end %>
This is the migration file of InnerObjects.
class InnerObjects < ActiveRecord::Migration
def self.up
create_table :inner_objects do |t|
t.string "name"
t.boolean "is_white", :default => true
t.timestamps
end
end
def self.down
drop_table :inner_objects
end
end
I found a similar question but could not retrieve an answer for me.
The question is: How can access the attribut is_white? My example does NOT work.
Try
<% if f.object.is_white == true %>
Seem to remember you could access the object this way (not 100% sure though ;)
Is it because f.is_white is based on a blank object in the partial? Try
<%= form_for #outer_object do |f| %>
<%= f.fields_for f.inner_object do |builder| %>
<%= render :partial => "inner_object_form_fields", :locals => { :f => builder } %>
<% end %>
<% end %>
That way it's referencing the attached object and any state you've created.
Even one step further would be to do something like this:
<%= f.fields_for f.inner_object do |builder| %>
<%= render :partial => "inner_object_form_fields", :locals => { :f => builder, :inner_object => builder.object } %>
<% end %>
Then you can do.
<% if inner_object.is_white == true %>
This way your partials code looks a little cleaner.

How do you pass rails 3 forms params into an array?

I have a nested form (using accepts_nested_attributes_for in respective models):
<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>
<%= f.fields_for :service do |s| %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<% end %>
<% end %>
This works fine if I only have one s.text_field. But once I add additional text_fields, it doesn't run properly. If you look at the source code, the id and name are the same for all six?
How do I put these params into an array? [so that I can isolate them like this:]
service1 = Service.named(params[:technician][:service][1][:name])
(I've tried the method described on railscasts episode 192, but it didn't work either).
After hours of trial and error, I've hacked something that works (but please let me know if you know a better, more eloquent way):
in view:
<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>
<% for #i in 1..6 do %>
<%= f.fields_for "services[#{#i}]" do |s| %>
<% end %>
<% end %>
<% end %>
in controller:
for i in 1..6 do
#service = Service.named(params[:technician][:services][i.to_s][:name]).first
end
make sure you turn i into string