I have two models, posts and comments, and i am trying to show the last 5 comment titles.
<%= Post.limit(5).order('created_at desc') %>
gives me the last 5 posts.
How do i get the last 5 comments and just the titles?
For getting just last 5 comments, you can use this
Comment.limit(5).order('created_at desc').select(:title)
Showing the title of the post, it looks like that you want to retrieve the last 5 comments of a post.
You can get this way:
<% Post.limit(5).order('created_at desc').each do |post| %>
<% post.comments.select(:title).order('created_at desc').limit(5).each do |comment| %>
<%= comment.title %>
<% end %>
<% end %>
There are two problems:
You're accessing the model directly from View. You should do it from
Controller
There is N + 1 problem. You can solve it by eager loading associations
Note: I couldn't test these but I guess they will work or will, at least, give you idea.
I think you are looking for:
Comment.select(:title).order('created_at desc').limit(5).map {|c| c.title}
This will give you an array of titles for the last 5 comments created. If you need other attributes, either add them to the select method called (Comment.select([:title, :owner])), or remove the select and fetch all comment attributes.
Related
I have 2 Models in my application. Project & Note. A project has_many notes. This all works great but on the projects index page.html.erb I would like to show the last note for a project.
My question is how do I retrieve this and then display it, on the index screen?
You can get the last note using project.notes.last. In your view, add below :
<% projects.each do |project| %>
<% last_note = project.notes.last %>
<%= last_note.note unless last_note.nil? %> # get last note per project if it exists
<% end %>
In my app to learn RoR, I want to get the last x (say 5) records in a list.
Currently I get all using
<% #business_partner.received_documents.each do |document| %>
Looking at documentation and SC posts, I tried using this code below, yet get an empty list.
<% #business_partner.received_documents.last(5) do |document| %>
what should I use?
Order received_documents by the creation date and take 5 last:
#business_partner.received_documents.order(:created_at).limit(5)
To get 5 newest ones you'd do:
#business_partner.received_documents.order(created_at: :desc).limit(5)
EDIT
The problem with this
#business_partner.received_documents.last(5) do |document|
is that you actually do not iterate over the collection, thus no output is shown.
Use each:
#business_partner.received_documents.last(5).each do |document|
You Forget to User each In Your Code
<% #business_partner.received_documents.last(5).each do |document| %>
In my Rails 4 app, I am using paper_trail to track changes made by users on the records of the Post model:
# post.rb
has_paper_trail :on => [:update, :destroy]
A post belong_to a calendar and a calendar has_many post, so I display the changes made to posts in a dashboard located in the calendar index view:
<div id="my_changes">
<% if #versions.any? %>
<% #versions.each do |version| %>
<% version.reify ? post = version.reify : post = Post.find_by_id(version.item_id) %>
<p>
<strong>
<% if version.whodunnit.to_i === current_user.id %>
You
<% else %>
<%= User.find_by_id(version.whodunnit).first_name %>
<% end %>
</strong> <%= conjugate(version.event) %> the post "<%= post.subject %>" in the <em><%= link_to Calendar.find_by_id(post.calendar_id).name, calendar_path(id: post.calendar_id) %></em> calendar <span id="update_time_ago">— <%= time_ago_in_words(version.created_at) %> ago.</span></p>
<% end %>
<% else %>
<p>
<span class="glyphicon glyphicon-hand-up" aria-hidden="true"></span><br/>There is no change to your posts yet.<br/>
As soon as you update your calendar, a history of your changes will appear here.
</p>
<% end %>
</div>
This is working fine.
What I would like to achieve now — and I can't figure out how — is not only to display which post has been updated, but also which attribute of the post has been updated and its value.
For instance, instead of:
User_1 updated the post "Test post" in the Test calendar — 3 days ago.
I would like to have something like:
User_1 updated the date / time / subject / copy / of the post "Test
post" to NEW_POST_ATTRIBUTE_VALUE in the Test calendar — 3 days ago.
—————
UPDATE: I did read paper_trail's documentation, in particular the Choose attributes to monitor section, but this does seem to explain how to achieve what I am trying to achieve.
—————
UPDATE 2: I understand that what I am looking for may actually be explained in the Diffing versions section of the documentation.
So, I guess in my index.html.erb view, I could do something like:
post.versions.last.changeset
But then, how can I extract from there the information that I am interested in, eg: only the attribute that was updated, and its new value, and not the updated_at attribute, that I cannot ignore with paper_trail since I still want to know when the post was updated?
—————
UPDATE 3: in this Stack Overflow thread, #Maysam suggests:
With this behavior enabled, it is reasonably simple to get
object.versions.map{|v| [v.created_at, v.changeset]} and then
iterate over that structure to render your change log.
I am not sure I understand how I can actually iterate over that structure in my case: any suggestion?
—————
Can I actually achieve that with paper_trail?
.. I would like to .. display .. which attribute of the post has been updated and its value.
Per the documentation on Diffing Versions:
.. to diff adjacent versions .. add an object_changes text column to your versions table .. PaperTrail will store the changes diff .. in each update version. You can use the version.changeset method to retrieve it.
So, once you've done that, try adding
= debug post.versions.last.changeset
To your view. After that, if you know how to work with hashes in ruby, you should be good to go.
Im trying to create a system which allows athletes to respond to their coaches traing plan, to do this i have allowed the coach to create contentsm however i am using a blogging based system to create it... at the moment the page displays like so
CONTENT TITLE
Content info 1...
Content info 2...
Content info 3...
COMMENTS...
comment 1
comment 2
comment 3
.etc
However i want to set it so that there can only be 7 Comments Max per post as well as set out like this per post...
CONTENT TITLE
Content info 1...
comment 1
Content info 2...
comment 2
Content info 3...
comment 3
.etc
I realise this is probably not the best way to do want i want, but it works (just dosnt appear in the place i want it to)
I did do experiments with creating more models, but kept getting errors whenever i tryed to run more than 1 comment system per post. I was wondering if i could have some help in sorting this out, or any methods i could do to make this easier, or even better if the models would work and if i was just doing something wrong?? tell me if this isn't enough information to go off, and ill try provide some more! Thankyou
.
.
EDIT:
The models i have used are
Program - As in the training plan set for the week
Coaches - The coach that is inputing the data to the rider
Riders - To comment on the coaches data with their own data.
I am unsure what files are need exactly so i have included the link to the github page i am pushing to ( https://github.com/effectonedesign/coacheasy1 ), if there is any other info needed, please let me know!
I like what "mind" has said however, i have done everything have said, in my def show (program controller) it is saying there is an error and i keep getting this message undefined method `coaches' for nil:NilClass everything is identical to his but im getting issues, i really do appreciate the help! Thanks
I would probably create 3 models for the above, TrainingPlan, Section (or content, text_block etc.) and Comment.
Then do the following
TrainingPlan has_many :sections
Section belongs_to :training_plan
Section has_one :comment (if you allow only 1 comment per section, otherwise use has_many)
Comment belongs_to :section
Now, to achieve the formatting you wanted do the following in your views:
<% #training_plan.sections.each do |section| %>
<%= section.text %>
<%= section.comment.text %>
<% end %>
If you allow multiple comments:
<% #training_plan.sections.each do |section| %>
<%= section.text %>
<% section.comments.each do |comment| %>
<%= comment.text %>
<% end %>
<% end %>
Form for comments
I haven't tested the following, so you might need to tweak some parts.The training plan controller:
def show
# using includes will query the database 3 times only (once for each table) rather than
# querying it 1 + N + N (in this case 7 sections, 7 comments possibly, so 15 times)
#training_plan = TrainingPlan.includes(:sections, sections: :comment).find(params[:id])
#sections = #training_plan.sections
#sections.each do |section|
# only build a new comment if there is no comment for that section already
section.build_comment unless section.comment
end
end
In your view views/training_plans/show.html.erb
<%= #training_plan.title %> # or whatever
<% #sections.each do |section|
<%= #section.content %>
<% if section.comment %>
<%= section.comment.content %>
<% else %>
<%= render 'comments/form', comment: section.comment %> # or wherever you have the form
<% end %>
<% end %>
views/comments/_form.html.erb
# This might break if you have a separate comment action somewhere which passes an
# instance variable #comment to the form
<%= form_for comment do |f| %>
# normal form stuff
<% end %>
If that all works then on your training plan show page you should see each section, and if it has a comment then that comment will be rendered, otherwise a form will be shown.
Depending on your routes you might need to run rake routes and see where your comment create action is, and then pass that to the form <%= form for comment, url: some_url_helper_here do |comment| %>
If it was me I would create the add comment part through JavaScript, sort of like in this railscast, but since you're new to RoR I've tried to keep it simple.
I have an object called #events containing about 50 records being pulled from a find condition of my model.
I'm currently displaying the results of the #object in my view like this....
<% for event in #events %>
<p><%= #event.name %></p>
<% end %>
Instead of displaying the entire 50 I would like shrink the set to about 10 records so it displays better on the page.
I cannot use :limit in the find condition since the object is being composed from a variety of loops where after each iteration it adds a few specific records.
So the issue is I have this object #events with 50 records, how can I change the object after its been composed so only the first 10 records remain?
First of all, if you'd like to have pagination, I strongly suggest taking a look at will_paginate
Alternatively, you can do the following to read the first 10 records only.
<% #events.first(10).each do |event| %>
<p><%= event.name %></p>
<% end %>
Or the last 10 records
<% #events.last(10).each do |event| %>
<p><%= event.name %></p>
<% end %>
I didn't test it but you get the point.
are you looking to completely do away with the other 40 or are you just wanting to pull off 10 per page for display purposes. if you are just doing this for display purposes i would look into the will_paginate gem. through its options you could set it so only 10 results per page are shown.
Take a look at will_paginate and kaminari. They both are designed to limit the records retrieved from the database, plus offer helpers for your views to provide the usual number of pages and current page lists.
Will_paginate has been around a while, and is pretty flexible. Kaminari is newer and looks like it has a cleaner interface.