Rails 3 radio button values from a mapped array - ruby-on-rails-3

UPDATE: THE CODE IN THIS POST HAS BEEN CHANGED TO THE WORKING SOLUTION.
To make radio buttons display stored values from a mapped array.
Controller:
#questions = Question.all
#ans = Answer.where(user_id = current_user.id)
#answers = #questions.map { |q| [q, #ans.find_by_question_id(q.id)] }
View:
<% #answers.each do |q| %>
<%= q[0].question %> [<%= q[1].id %>] <%= q[1].score %>
<% [ 1, 2, 3, 4, 5 ].each do |f| %>
<%= radio_button_tag q[0].name, f, f == q[1].score %>
<% end %>
<br />
<% end %>

edit: oops... forgot the # on answers.each. fixed
<% #answers.each do |q| %>
<%= q[0].question %>
<% [1..5].each do |f| %>
<%= radio_button_tag 'score', f, (f == q[1].score).to_s %>
<% end %>
<br />
<% end %>
Its off the top of my head but basically you have to pass true or false not the number checked. I'm assuming that q[1].score is a number from 1 to 5

Hey, folks. Thanks for your help. Mike, you were close. There were two problems. First, the name "score" would be assigned to every button for every question. The name needs to be the same for every button for one question, but needs to change on the next question. See q[0].name below. Second, the score is numerical, not a string. So "to_s" resulted in every button being checked as it was made. Since there could only be one button checked per set, checking every button resulted in the last button being checked for each set. (e.g. the score 5 being checked each time)
<% #answers.each do |q| %>
<%= q[0].question %> [<%= q[1].id %>] <%= q[1].score %>
<% [ 1, 2, 3, 4, 5 ].each do |f| %>
<%= radio_button_tag q[0].name, f, f == q[1].score %>
<% end %>
<br />
<% end %>

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