I'd like to group a collection alphabetically by title:
#projects = Project.find_all_by_user_id(current_user.id)
The view should contain a list of projects grouped by title, e.g.:
A
Andre's Project
Ananas
C
Chemnitz
Cleopatra
F
Find a new office
S
Super secret stuff
But I got no clue how to do this in rails. Does rails provide a functionality to do this or do I need to write my own loop looking for the titles etc.?
Thank you!
Not Rails but Ruby does the trick. In your view:
<% #projects.group_by{ |project| project.name[0].downcase }.each do |letter, projects| %>
<div id="letter-<%= letter %>" class="letter-group">
<h2><%= letter.upcase %><h2>
<% projects.each do |project| %>
<p><%= link_to project.name, project %></p>
<% end %>
</div>
<% end %>
group_by (ruby-doc) returns a hash you can easily loop through with letters as keys and arrays of corresponding projects as values. Be sure to already get your records sorted by project's name: (in your controller)
#projects = Project.order("name ASC").find_all_by_user_id(current_user.id)
Related
I've got a collection_select instance in a form, and I'm wondering if it's possible to have two or more instances in the same form. They'd be built from the same model, and they would save as if they were checkboxes constructed in an Article.all.each loop. To have these work
<%= f.collection_select("article_ids", Article.where(:page => 1), :id, :name) %>
<%= f.collection_select("article_ids", Article.where(:page => 2), :id, :name) %>
<%= f.collection_select("article_ids", Article.where(:page => 3), :id, :name) %>
in the form is pretty much what I'm after. It's essentially a multiple select but spread over a couple of selects. The field already accepts multiple results, but when I save the form as it is above it only records the option from the final select. Any thoughts?
Cheers!
<%= select_tag "article_ids[]",options_from_collection_for_select(Article.all.collect{|i| [i.name,i.id]),:multiple => true %>
When select multiple options in select list just give article_ids[] , it will store all ids in this array then after you write query how you would store in database.
If set the select tag is multiple true then you will select multiple options other wise you get only one selected value.
or just read below link
http://api.rubyonrails.org/?q=collection%20select
If you want to give f.select then you must give like this
<%= f.collection_select :article_id, Article.all, :id , :name %>
I just went with checkboxes to solve this, because it's truly the stuff of nightmares.
<% #articles.each do |a| %>
<%= check_box_tag("doc[article_ids][]", a.id, #doc.articles.include?(a.id), :class => "article_chooser") %> <a id="<%= a.id %>" class="name"><%= a.name %></a><br />
<% end %>
I have a rails app that gives users assignments and prompts them via email to come back and note that their assignment is completed or take some other action. I have three different actions (remind me later, choose a different assignment, or get help from a coach) which are represented by three radio buttons. How do I group these so that the user can only choose one of the three actions at a time?
<%= form_for(#assignment, :url => user_assignment_path(#user, #assignment)) do |a| %>
<%= a.radio_button :next_reminder_date, value: (Date.today + 2) %> <h3>Remind me again in 2 days.</h3><br>
<%= a.radio_button :coach_requested, true %> <h3>I'm stuck! Have a coach contact me.</h3><br>
<%= a.radio_button :abandoned, true %> <h3>This sucks. Give me another assignment.</h3><br>
<%= a.submit "Update assignment", class: "btn btn-primary btn-large" %>
<% end %>
I think you have two options. One would be to set the values using JavaScript. When any of the values is set, you can reset the other values. This won't work if a user doesn't have JavaScript so I'd recommend option 2.
Use something like this in your View:
radio_button_tag :next_action, :next_reminder_date
radio_button_tag :next_action, :coach_requested
radio_button_tag :next_action, :abandoned
Then in your Controller:
case params[:next_action]
when :next_reminder_date
#assignment.next_reminder_date = Date.today + 2
when :coach_requested
#assignment.coach_requested = true
when :abandoned
#assignment.abondoned = true
end
I hope that helps.
I have a list of organisations, grouped and displayed by their name, in alphabetical order. I want to display these across 4 columns for each letter, i.e.:
A
A... A... A... A...
A... A... A... A...
...
Z
Z... Z...
I have used the following code:
<% #organisations.keys.sort.each do |starting_letter| %>
<div class="page-chunk default">
<h6><%= starting_letter %></h6>
<% #organisations[starting_letter].each do |organisations| %>
<% organisations.in_groups_of(4).each do |column| %>
<div class="one_quarter">
<% column.each do |organisation| %>
<%= link_to organisation.name, organisation_path(organisation) %><br />
<% end %>
</div>
<% end %>
<% end %>
</div>
<% end %>
And in the controller:
#organisations = Organisation.all.group_by{ |org| org.name[0] }
But get undefined methodin_groups_of' for #for my troubles. If I change the code to#organisations[starting_letter].in_groups_of(4).each do |organisations|then I get aNilClass` error.
What have I done wrong and how should I fix it?
Try organisations.in_groups_of(4, false)
Without the false, it will fill in any empty spots in the last group with nils, which means it will try to call name on nil.
I have a radio_button_tag in a form, which holds various values for a persons current availability:
Mike Donnall o Available o Out of office o Vacation
So originally you open the form, and select a value, this then sets the value in the Status table for that Person.
However, there's also functionality to re-open the form and update his present status, perhaps from Vacation to Available.
My question is, is there anyway at all that radio button :checked can be modified to accept a custom method, I have found something in a similar posting, but I want the value foe that radio button to be set to the value in the DB.
My code so far, a stab in the dark perhaps:
View:
<% #people.each do |p| %>
<% #statuses.each do |s| %>
<%= "#{p.name}" %>
<%= "#{s.status_name}" -%><%= radio_button_tag ['person', p.id], ['status',
s.id], checked?(p.id) %>
<% end %>
<% end %>
Helper:
def checked?(person)
#person = person
#status = Status.find_by_sql(['select status_id from statuses where person_id = ?, #person])
if #result
return true
end
As you can see Im a bit lost here, but I understand that the method should return the value of the checkbox that needs to be checked, but Im wondering because its a checked functionality, would it only be limited to being a true or false?
So for a persons.status.id check if its true or false.
It seems from your helper's SQL that you the following relationship setup between People and Statuses:
class Person < ActiveRecord::Base
has_one :status
end
class Status < ActiveRecord::Base
belongs_to :person
end
You can access one given person status like this:
person = Person.first
person_status = person.status
Using that knowledge, your desired view outcome becomes quite simple:
<% #people.each do |p| %>
<p><%= "#{p.name}" -%>
<% #statuses.each do |s| %>
<%= "#{s.status_name}" -%>
<%= radio_button_tag ['person', p.id],
['status', s.id],
(p.status == s) ? true : false %>
<% end %>
<% end %>
You can of course extract the logic to a helper, but that doesn't seem necessary.
On a personal note, this isn't the way I'd present the information to user, it' too heavy on information in one line. I suggest you put the person's name in a p tag, and use a ul tag for the statuses.
I have a HABTM-relation between the models "Snippets" and "Tags". Currently, when i save a snippet with a few tags, every tag is saved as a new record.
Now i want to check if a tag with the same name already exists and if that´s the case, i don´t want a new record, only an entry in snippets_tags to the existing record.
How can i do this?
snippet.rb:
class Snippet < ActiveRecord::Base
accepts_nested_attributes_for :tags, :allow_destroy => true, :reject_if => lambda { |a| a.values.all?(&:blank?) }
...
end
_snippet.html.erb:
<% f.fields_for :tags do |tag_form| %>
<span class="fields">
<%= tag_form.text_field :name, :class => 'tag' %>
<%= tag_form.hidden_field :_destroy %>
</span>
<% end %>
Ok, i´m impatient… after a while i found a solution that works for me. I don´t know if this is the best way, but i want to show it though.
I had to modify the solution of Ryan Bates Railscast "Auto-Complete Association", which handles a belongs_to-association to get it working with HABTM.
In my snippet-form is a new text field named tag_names, which expects a comma-separated list of tags.
Like Ryan, i use a virtual attribute to get and set the tags. I think the rest is self-explanatory, so here´s the code.
View "_snippet.html.erb"
<div class="float tags">
<%= f.label :tag_names, "Tags" %>
<%= f.text_field :tag_names %>
</div>
Model "snippet.rb":
def tag_names
# Get all related Tags as comma-separated list
tag_list = []
tags.each do |tag|
tag_list << tag.name
end
tag_list.join(', ')
end
def tag_names=(names)
# Delete tag-relations
self.tags.delete_all
# Split comma-separated list
names = names.split(', ')
# Run through each tag
names.each do |name|
tag = Tag.find_by_name(name)
if tag
# If the tag already exists, create only join-model
self.tags << tag
else
# New tag, save it and create join-model
tag = self.tags.new(:name => name)
if tag.save
self.tags << tag
end
end
end
end
This is just the basic code, not very well tested and in need of improvement, but it seemingly works and i´m happy to have a solution!