I've been trying got find this answer, and maybe it's too simple...
In rails, how is the best way to iterate through results from activerecord pull the specific fields that you want?
I have a controller for comments (named posts) that pulls all records:
def index
#posts = Post.find(:all)
end
Then in the index view, when I use <%= #posts %> I get all of the data...which is great...
#<Post id: 1, user_id: "9", picture: nil, comments: "here's a first comment", title: nil, twitter: nl, frame: nil, created_at: "2012-05-09 04:21:16", updated_at: "2012-05-09 04:21:16"> #<Post id: 2, user_id: "9", picture: nil, comments: "here's a second comment", title: nil, twitter: "please", frame: nil, created_at: "2012-05-09 05:20:03", updated_at: "2012-05-09 05:20:03">
How can I now iterate through test so that the view shows the data from the comments and created_at fields:
Here's the first comment, 2012-05-09 04:21:16
Here's the second comment, 2012-05-09 05:20:03
I've tried the following and get an error.
<% #posts.each do |c| %>
<%= c.posts.comments %>
<%= c.posts.created_at %>
<% end %>
The "c" in #posts.each do |c| represents the specific post object in the #posts collection.
So, in a sense you are trying to do <%= post.posts.comments %>.
Here's how the code should look:
<% #posts.each do |p| %>
<%= p.comments %>
<%= p.created_at %>
<% end %>
Change things to this:
<% #posts.each do |post| %>
<%= post.comments %>
<%= post.created_at %>
<% end %>
I find it makes it easier for people to follow if you name the inner variable as the singular of the out variable -- therefore #posts on the outside becomes post on the inside.
Good luck!
Related
So I'm using the following in both my show and index:
<%= image_tag posts.avatar(:large), alt: 'Avatar for #{posts.title}', class: 'img-responsive' %>
Since they are the same in both I'm trying to move them to a view helper. Then in my views I'm putting:
<%= post_image_tag %>
My initial take was the following:
def post_image_tag
image_tag posts.avatar(:large), alt: 'Avatar for #{posts.title}', class: 'img-responsive'
end
I end up with : undefined local variable or method `posts' for #<#:0x007fcdd273e860>
Did you mean? #posts
Cool. So I change it to:
def post_image_tag
image_tag #posts.avatar(:large), alt: 'Avatar for #{posts.title}', class: 'img-responsive'
end
Now I end up with: undefined method `avatar'.
So I decided that it might just be that I'm not referencing it correctly and trying to pull ActiveRecord on a single post so I try:
def post_image_tag
#posts.each do |posts|
image_tag posts.avatar(:large), alt: 'Avatar for #{posts.title}', class: 'img-responsive'
end
end
At this point something FINALLY renders on the page. Except it looks like an HTML nightmare with:
[#<SpudPost id: 1, spud_user_id: 2, title: "The Top ", content: "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transi...", comments_enabled: false, visible: true, published_at: "2018-01-30 14:45:58", created_at: "2018-02-05 17:41:42", updated_at: "2018-02-05 17:41:42", url_name: "the-top", is_news: false, meta_keywords: nil, meta_description: nil, content_format: "HTML", content_processed: nil, blog_key: "blog", custom_author: nil, identifier: "9b0d97c9-6855-4ad6-85ac-cade6012b5de", avatar_file_name: "ice.jpg", avatar_content_type: "image/jpeg", avatar_file_size: 68494, avatar_updated_at: "2018-02-05 17:41:40">,
It goes further repeating the next item and the next, etc. What in the world can I put on the image_tag to make it render correctly? I've also tried changing the view helper in my view to:
<%= raw(post_image_tag)%>
Then I end up with [#, #, #, #]
You took a wrong turn in this rabbit hole. Go back to your first version of the helper and pass the post as parameter
def post_image_tag(post)
image_tag(post.avatar(:large), alt: 'Avatar for #{post.title}', class: 'img-responsive')
end
# this "posts" should really be named "post", since it's a single post,
# not a collection of them.
<%= post_image_tag(posts) %>
The image is for 1 post, so you should name the variable 'post' and not 'posts'. Anyway this is just for clarity and not an error.
You can define a helper that accepts a param:
def post_image_tag post
image_tag post.avatar(:large), alt: 'Avatar for #{post.title}', class: 'img-responsive'
end
and call it this way (assuming post is 1 post):
<%= post_image_tag(post) %>
If you have many posts in #posts, you should do:
<%= #posts.each do |post| %>
<%= post_image_tag(post) %>
<% end %>
You can also make another helper to handle many posts (it may need some changes, but you get the idea):
def posts_image_tag posts
result=''
posts.each do |post|
result += post_image_tag(post)
end
result.thml_safe
end
and call it this way (assuming #posts has all your posts):
<%= posts_image_tag(#posts) %>
I have the following view:
# index.html.web
<h1>Listing answers</h1>
<%= will_paginate %>
<%= render [#answers]%>
<%= will_paginate %>
And the following index action:
def index
#question = Question.find(params[:question_id])
#answers = #question.answers.paginate(page: params[:page])
respond_with(#answers)
end
I'm getting the following errror:
ActiveRecord::AssociationRelation [#<Answer id: 2, content: "b", user_id: nil, question_id: 1, created_at: "2015-04-27 14:59:32", updated_at: "2015-04-27 14:59:32">, #<Answer id: 3, content: "d", user_id: 1, question_id: 1, created_at: "2015-04-27 15:15:01", updated_at: "2015-04-27 15:15:01"] is not an ActiveModel-compatible object. It must implement :to_partial_path.
How can I fix it?
You can do it in two different ways.
<%= render #answers %> OR
<%= render partial: 'answer', collection: #answers %>
In both cases, you will get an object named answer in partial view.
And you must have a file named _answer.html.erb should exists in same directory.
When you pass a collection of instances to render the partial, you don't need to put any square bracket around the instance.
<%= render #answers %>
And don't forget to create a view name _answer.html.erb as well
source: http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables
index.html.erb
<h1>Listing answers</h1>
<%= will_paginate #answers%>
<%= render #answers%>
<%= will_paginate #answers%>
There must be a partial called _answer.html.erb
The above mention line will call _answer.html.erb with answer object in a loop.
I am displaying all of a user's posts in my users#show view, and it is working fine except for an array of all the user's posts is being returned after the actual posts. Here is the show action for the users controller:
def show
#user = User.find(params[:id])
#posts = #user.posts.all
end
users/show.html.erb
<div class="profile">
<%= image_tag #user.image.url(:thumb) %>
<h4><%= #user.name %></h4>
</div>
<div class="userposts">
<%= #posts.each do |post| %>
<h8><%= link_to post.title, post_path(post) %></h8>
<p><%= truncate(post.content, length: 250, omission: '... (continued)') %></p>
<% end %>
</div>
Here is the unwanted array being returned:
Post id: 1, title: "post", content: "content", created_at: "2014-12-02 14:07:43", updated_at: "2014-12-02 14:07:43", user_id: 1 Post id: 2, title: "Another Post", content: "more content", created_at: "2014-12-02 14:29:26", updated_at: "2014-12-02 14:29:26", user_id: 1
Change this <%= #posts.each do |post| %> to this <% #posts.each do |post| %>.
In erb <%= means the evaluated code will be printed out.
In my Rails app I'm trying to loop over the Submission instances inside my Folder instances with Rails templating code. It works. However, it's also returning each instance in code which doesn't seem to be JSON. It's what's returned when you look up an instance in the Rails console. Here's an example:
#<Submission id: 112, title: nil, content: nil, created_at: "2013-10-10 23:29:39", updated_at: "2013-10-10 23:29:39", user_id: 1, folder_id: 1, parent_id: nil>
Here's what the code looks like for the loop:
<%= #folder.submissions.each do |x| %>
<% if x.title != nil %>
<div id="<%= x.id %>" class="submission-textual">
<h1><%= x.title %></h1>
</div>
<% else %>
<% end %>
<% end %>
I checked my Folder and Submissions controllers but am not sure what this is. Why are these strings being rendered whenever I try and render an instance in my view? I'm still new to Ruby so that explains why I haven't seen this.
Try replacing the first line with
<% #folder.submissions.each do |x| %>
It's a small diffrerence, the equal sign after the first % was removed. I think that's what's causing the unwanted rendering.
The processing is as follows :
<% "ERB will evaluate this!" %>
<%= "ERB will evaluate and output this!" %>
I'm sort of new to Ruby on Rails and have been learning just fine, but have seem to run into a problem that I can't seem to solve.
Running Rails 3.0.9 & Ruby 1.9.2
I'm running the following statement in my View:
<%= #events.each do |f| %>
<%= f.name %><%= link_to "View", event_path(f) %><br/><hr/>
<% end %>
And this in my controller:
class AdminController < ApplicationController
def flyers
#events = Event.all
end
end
This goes through each of the records and outputs the appropriate name, but the problem is that at the end it displays all of the information for all of the records like so:
[#<User id: 1, username: "test account", email: "test#gmail.com", password_hash: "$2a$10$Rxwgy.0ZEOb0lMGEIliPBeB/jPSp8roeKdbMvXcLi32R...", password_salt: "$2a$10$Rxwgy.0ZEOb0lMGEIliPBe", created_at: 2111359287.2303703, updated_at: 2111359287.2303703, isadmin: true>]
I'm new to this site, so I'm not sure if you need any more details, but any help is appreciated, after all, I'm still learning.
Thanks in advance.
You should be using <%, not <%= for your .each line, so
<%= #events.each do |f| %>
should be
<% #events.each do |f| %>
.each returns the entire array at the end once it is finished the loop.
<%= ... %> prints out the value of the statment, which is the value returned by .each
<% ... %> does not. So you want:
<% #events.each do |f| %>
<%= f.name %><%= link_to "View", event_path(f) %><br/><hr/>
<% end %>