Ruby on Rails: bookmarks buffer collection content_tag excerpt helper methods loop Rails visual markup
by bseanvt
leave a comment
Simple String Concatenation of a Collection Written as a Helper for Rails
At Railsconf last week I took Greg Pollack’s online course Rails Best Practices. The interface is gorgeous and the instructions are excellent. One of the lessons involved taking a partial and moving it into a helper. I was reminded how difficult such a simple task can be. I have written about this before Yield a Block Within Rails Helper Method with Multiple Content Tags. However, that post aims to solve a slightly different problem, where the helper method takes the captured text from a block passed as an argument which essentially acts as a wrapper.
The difficulty isn’t with the logic itself and or the complexity/verbosity that the code is likely to produce. Rather, it is difficult because you have to endlessly concatenate strings and this something somewhat uncommon when programming with ruby. We have to remember that we’re working with a buffer of text about to be flushed. Here is a simple code snippet that shows how to write a helper method that loops over a collection of objects.
def bookmarks_for(user=nil)
content_tag(:div, :id => "bookmarks") do
user.bookmarks.each do |bookmark|
concat(
content_tag(:strong) { bookmark.member_name } +
excerpt(bookmark.body, '', 100)
)
end.join
end
end
Notice the use of the concat() method the “+” sugb and .join() method. All three of which bring these statements together into one final piece of html called in the view.
<%= bookmarks_for(@user) %>
Posts Ruby on Rails: api collection helpers html select
by bseanvt
leave a comment
Collection Select Helper and OnChange Event in Rails
Given a collection of Active Record objects, you may use the collection_select helper method to produce a select form field. You need to pass in a number of arguments to the helper function.
1) object – your model object used in the collection
2) method – a valid model attribute or method
3) collection – a collection of active record model objects
4) option_value – value being set from the model for the <option value=”option_value”> html element
5) option_name – what is displayed for the user e.g., <option> option_name <
6) option – general options
7) options for the select html element
# helper and arguments...
# collection_select( model, id, collection, option_value, option_name, options, html_options)
<%= collection_select("states", "state_id",
State.participating,
"abbreviation", "name",
{:selected=> get_current_state_or_nil },
{:onchange=>"document.location='/states/'+this.value"}
) %>
#which will produce something like...
<pre id="line27"><select id="state_id" name="state[id]" onchange="document.location='/states/'+this.value">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
</select>


