Rails: Count variable in view - ruby-on-rails

Hey! I iterate through a hash with #lists.each do |list|. I create a div in every cycle that must have an id. I would have created a count variable in PHP to get a definite id. What is the best way to do that in a Rails view? Thank you!

Assuming these are ActiveRecord models (ie. from a database), you could just use the dom_id helper, like so:
<% #lists.each do |list| %>
<div id="<%= dom_id(list) %>">
... rest of list ...
</div>
<% end %>
That way each div will get an ID like list_49, with the number corresponding to the ID in the database.

An alternative would be to use the div_for helper:
<% #lists.each do |list| %>
<% div_for(list) do %>
... content in div ...
<% end %>
<% end %>
That will add the same format of id as Luke's suggestion. Be aware though that it would also add a class attribute of list. You can add additional classes by passing in :class => 'my-class'.

Why don't you just take the id of the list? Or must the id be any kind of "globally unique"?
Update: I think you should go with luke's answer.

Related

passing a hash to a route in rails

In the preview action in my controller, I have
#models = Model.all
In the view, Im trying to loop through all the models, draw out their associated images, and use those to link_to their own profiles.
<% #models.each do |m| %>
<div> <%= link_to(image_tag (m.avatar.url(:thumb)), model_path())%> </div>
<% end %>
I need to pass in the id of each model to the route. Using m.id doesn't work because the route is expecting a hash.
Not entirely sure how to do this. Other posts on SO refer to unsaved instances and such, which aren't really relevant to this.
Try changing your view code from this:
<% #models.each do |m| %>
<div> <%= link_to(image_tag (m.avatar.url(:thumb)), model_path())%> </div>
<% end %>
To:
<% #models.each do |m| %>
<div> <%= link_to(image_tag(m.avatar.url(:thumb)), model_path(m))%> </div>
<% end %>
As usual the error might be in a completely different place - your brackets.
model_path can accept both list of attributes and a hash. Most likely you think it is expecting a hash due to the error message (which you should include in the question). In fact however, you are passing the path to the image_tag, not to the link_to:
link_to(image_tag (m.avatar.url(:thumb)), model_path())
is parsed as
link_to( image_tag(m.avatar.url(:thumb), model_path()) )
While:
link_to(image_tag (m.avatar.url(:thumb)), model_path())
is parsed as
link_to( image_tag(m.avatar.url(:thumb)), model_path() )
This space between a method name and a bracket is a silent killer. It is a image_tag which is expecting a hash in a second argument. :)
That being said - it will still not work, but you should get a different problem now.

How to count associated records in rails and display as an integer.

I have several items, each item also has several sub items.
I would like to strictly count the number of sub items attached to each item and display that as an integer. Is there a way to do this?
I tried this, but it does not seem to return correctly.
<div class="items" id="cell"><%= sub_item.count %></div>
Something like this should work, can you add your objects structure?
<% #items.each do |item| %>
<div>Count: <%= item.subitems.count %></div>
<% end %>
I am assuming you have a #items instance variable in your view, and for each item in items you have several item.subitems, so you could do something like this:
#items.each do |item|
<div class="items" id="cell">
<%= item.subitems.count %>
</div>
item.subitems.each do |subitem|
// Do stuff
end
end
Of course i could've assumed wrong.

Calling each article tag separately from within another loop

I have an article, and each article has tags. Right now I call all the tags together:
<% #articles.each do |article| %>
<div class="articlebox">
<article>
<h4>
<%= link_to article.title, article_path(article) %>
</h4>
<%= markdown article.body %>
<span class="articletagbox">
<%= article.tag_tokens %>
</span>
<% end %>
Right now my class goes around all the article tags. I want it to go around each article tag individually.
I've tried a simple
<% #tags.each do |tag| %>
but that gives me an undefined method "each" nilclass error.
I know this is pretty simple, but I just can't figure out what I'm supposed to change to make it work. I assume I need to define something in my article model?
Thanks!
EDIT
So right now my code looks like this:
<% article.tags.each do |tag| %>
<span class="articletagbox">
<%= article.tag_tokens %>
</span>
<% end %>
and the method in article.rb is:
def tag_tokens
self.tags.collect{|t| t.name}.join(", ")
end
which is returning all the tags associated with each article the same number of times as there are tags.
So for example, if I have three tags on an article: tag1, tag2, tag3 I get
<class>tag1 tag2 tag3</class> <class>tag1 tag2 tag3</class> <class>tag1 tag2 tag3</class>
Instead I want
<class>tag1</class> <class>tag2</class> <class>tag3</class>
So I'm just not sure why I'm getting all the tags associated with each article returned together, but the same number of times as there are tags. I hope that makes sense.
If one article has many :tags then in the article loop do
<% article.tags.each do |tag| %>
Following your edit : you're outputting a method called on the article while looping on tags. Doesn't make sense, you're looping on tags, call tag.name instead!
Check slhck answer for the specific syntax
You said you wanted:
<class>tag1</class> <class>tag2</class> <class>tag3</class>
I'm assuming by class you mean the span formatting that should be applied to each tag individually? Just get rid of the tag_tokens method. It would probably be bad style to define formatting methods in your tag's model anyway – rather do the formatting in a view, or a partial.
In your view, inside the loop where you go over all articles, just do:
<% article.tags.each do |tag| %>
<span class="articletagbox"><%= tag.name %></span>
<% end %>
This would output:
<span class="articletagbox">tag1</span>
<span class="articletagbox">tag2</span>
... and so on.

Rails - Easy way to display all fields in view

OK I'm sure I'm missing something here, but please forgive me I'm new to Rails.
Is there some way in Rails to display all the fields for an object rather than specifying each?
In my show.html template rather than going
<p>Name: <%=h #user.full_name %></p>
<p>Email: <%=h #user.email %></p>
I just want a oneliner to do this without having to type out each of the 15 or so fields I have.
Its an admin page so its fine if all the fields are shown (id, created_at, etc.)
If this was PHP it would take me about 5 secs using foreach, but I've googled (on the wrong things obviously) for an hour with no luck.
Thanks!
Something like
<% for attribute in #user.attributes.keys %>
<p><%= attribute.humanize %> <%= #user.attributes[attribute].to_s %></p>
<% end %>
could do the trick.
Matt
I suppose you want to display all attributes of a row from database table which is defined as ActiveRecord model. You can use class method column_names (every ActiveRecord model has it), which returns names of table columns in an array.
<%= User.column_names.collect { |col_name| "#{col_name.capitalize}: <p>#{#user[col_name]}</p>" }.join("\n") %>
<%= debug #user %>
simple way to show the object... that is what I usually use anyway!
#user.attributes.each{|key, value| puts "#{key} : #{value}"}
This is the snippet I used to blacklist some attributes I didn't want to show...
controller (user_controller.rb)
def show
keys_blacklist = %W(user_id name) #these are the fields to hide
#user_showlist = #user.attributes.except(*keys_blacklist)
end
view (show.html.erb):
<!-- language: ruby --><% for attribute in #user_showlist.keys %>
<b><%= attribute.humanize %></b>
<%= #user.attributes[attribute].to_s %>
<!-- language: ruby --><% end %>
You can also use instead:
#user_showlist = #user.attributes.slice(*keys_whitelist)
in order to display a whilelist of properties.
If you are using haml and want to loop through the attributes on for example a user object in a view:
- for attribute in #user.attributes.keys
%p
= attribute.humanize
= #user.attributes[attribute].to_s

Rails 'params' variable

In reference to this
I've created a question in a webform like this:
<div class="form_row">
<label for="features[]">Features:</label>
<% [ 'scenarios', 'role_profiles', 'private_messages', 'polls' ].each do |feature| %>
<br><%= check_box_tag 'features[]', feature,
(params[:features] || {}).include?(feature) %>
<% end %>
</div>
So if scenarios and private_messages gets checked and I print out params[:features] I will get:
scenariosprivate_messages
I was wondering how would I be able to obtain scenarios and private_messages separately from params. Is the mapping params[:features] = "scenariosprivate_messages" or is it really params[features] = ["scenarios", "private_messages"] ? If it's the latter how can I loop through them?
I write in my view:
<%= params[:features].each {|param|
param.capitalize
} %>
and I still just get scenariosprivate_messages printed.
Try this instead:
<% params[:features].each do |param| %>
<%= param.capitalize %>
<% end %>
The problem with your original solution is that you're printing out the result of the block, which is the array itself, rather than printing out each element of the array.
You shouldn't be using params in your views. You're best off assigning params[:features] to an instance variable in your controller and then iterating over that in your view.
But to answer your question, you're putting the equals sign for output in the wrong place. You want to output each element of the array individually instead of outputting the result of the loop.
You must use humanize:
<% params[:features].each do |param| %>
<%= param.humanize %>
<% end %>
According to this blog post you should be able to access them individually as params[:features]['scenarios'] etc. Looping should just work like with all other arrays -- eg
params[:features].each { |param|
# do something with param
}

Resources