I followed the "Getting Started" tutorial at http://guides.rubyonrails.org/getting_started.html, and wanted to change what is output on the articles index page.
rather than showing the text of the article in the main table, I want to see the most recent comment made on that article.
Here is the code for the index:
<tr>
<td><%= article.title %></td>
<td><%= article.comments.select(:body).last %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
</tr>
Where 'article.comments.select(:body).last' is meant to show the body of the latest comment made on the article in question (this table iterates for every article).
Instead of seeing the text from the comment however, I see this:
{Comment:0x44f9ec8} (with sharp brackets instead of curly - wont let me post the sharp ones.... <>)
I also tried editing comment.create in the comments_controller with:
#article.text = #comment.body
After setting the index table field to 'article.text' (which works fine), but with no effect.
Anyone have any idea what I'm doing wrong??
Any help is much appreciated.
article.comments.select(:body).last does not do what you expect
the select part uses this select which alters the SQL command you use. It forces selecting only the body field from comments and returns a comment object.
so you need to change your code to article.comments.select(:body).last.body
If you need to have all the body fields and just use one, I suggest that you use pluck if you are on rails > 3.2
article.comments.pluck(:body).last
Related
This question already has answers here:
How do I pick randomly from an array?
(7 answers)
Closed 6 years ago.
I have an array of images that I want to shuffle and only show the first ten results. I am having trouble figuring out how to do that.
Here is my code
<% #images.each.shuffle do |image| %>
<tr>
<td><%= image.name %></td>
<td> <%= image_tag image.picture.url %></td>
<td><%= image.likes %></td>
<td><%= link_to 'Show', image %></td>
<td><%= link_to 'Edit', edit_image_path(image) %></td>
<td><%= link_to 'Destroy', image, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
You can use sample function in the Array class.
<% #images.to_a.sample(10) do |image| %>
If #images an AR proxy object or the result of some other DB query, you might want to adjust your query so that it does the shuffle-and-limit DB-side:
#images = Image.where(...).order("rand()").limit(10)
Note that sorting by random can't use indexes, but it's better than loading the whole table into RAM app-side. Something like this:
#images = Image.where(...)
#images.to_a.sample(10)
will load the results of the entire query into RAM in the Rails app, which will be quite slow.
This has the added benefit of keeping logic out of your views, which is a Rails best practice.
(Posted as an answer per asker's request)
Using Rails' resources directive, I have created a set of routes for a controller (contacts). I'm now editing the default views they come with to include some of my own content. However, the link_to method is failing, telling me that I'm missing a required parameter.
No route matches {:action => 'show', :controller => 'contacts', :id => nil} missing required keys [:id]
It's obvious why this is happening - the link_to method is not being supplied with an ID, instead it's getting nil. However, the code I'm using matches the documentation for link_to.
This is the view in question:
<% #contacts.each do |contact| %>
<tr>
<td><%= contact.first %></td>
<td><%= contact.last %></td>
<td><%= contact.title %></td>
<td><%= contact.city %></td>
<td><%= contact.phone %></td>
<td><%= contact.email %></td>
<td><%= link_to 'Show', contact %></td>
<td><%= link_to 'Edit', edit_contact_path(contact) %></td>
<td><%= link_to 'Delete', contact.id, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
#contacts is a set of contacts returned from the controller. The line that sets that is:
#contacts = Contact.select("title, first, last, city, phone, email")
.where("created_by" => #current_user.id)
The relevant content of the routes.rb file is simply resources :contacts.
The documentation states:
Because it relies on url_for, link_to supports both older-style controller/action/id arguments and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base your application on resources and use [...]
link_to "Profile", #profile
This appears to be what I'm using with link_to 'Show', contact.
Why is the ID not getting passed to link_to?
What can I do to remedy this?
Change
Contact.select("title, first, last, city, phone, email")
to
Contact.select("title, first, last, city, phone, email, id")
the contact's id is nil because it isn't in the select query.
Also, although it doesn't seem to be causing problems right now, I would reccomend using an array of symbols instead of a comma-separated string, so that the sql query is more specific. For example:
Contact.select("title, first").to_sql #=> SELECT title, first FROM contacts
Contact.select(:title,:first).to_sql #=> SELECT "contacts"."title", "contacts"."first" FROM contacts
This way if you do a join with another model, it won't complain about the unspecific id in select. If you feel like you're typing too much, you can use the %i(...) syntax:
Contact.select(*%i(title first last city phone email))
Your code seems fine.
Maybe you have an instance in the #contacts array that is not saved and therefore, has no id?
Another way to put the same (again, your code is fine) would be:
= link_to 'Show', contact_path(contact)
I would suggest posting the routes file.
<h1>Listing categories</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Thumburl</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #categories.each do |category| %>
<tr>
<td><%= category.name %></td>
<td><%= category.thumburl %></td>
<td><%= link_to 'Show', category_path(category) %></td>
<td><%= link_to 'Edit', edit_category_path(category) %></td>
<td><%= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<%= link_to 'New Category', new_category_path %>
So, as I said in my last post, I'm trying to go through Ruby code as I find it on Codecademy's RoR tutorial. Since they have such a straightforward tutorial, I figure it would be ridiculous to not understand everything they throw at me.
In this bit, they have an html.erb file that is supposed to form a tabled-view. Everything seems clear to me until they get to <tbody>.
Here, first, we are iterating on an instance variable #categories...now, where this instance variable is found, I don't know. I thought instance variables meant they could only be used within a particular class, yet this is a markup page, i.e. no classes have been defined, so how does Ruby know where or what this instance variable is?
Next: so, as I understand it, the word 'category', here, is serving as a variable because it was specified as such by pipe syntax two lines earlier. Now, whether this variable can be used beyond this html.erb page is beyond me, cause I thought instance variables were denoted with an '#.' With this variable, we call the method 'name'. So, is 'name' a custom method, and if so, where is it defined?
Now, the third <td> tag contains code that tells Ruby to link to some name 'Show,' yet I'm not sure what this name points to...also, 'category_path' is a method we defined in our routes.rb file, and it has the parameter of our blocked variable 'category.'
Lastly, the final row cell links to some name 'Destroy,' but this comma syntax is something I haven't seen before:
<td><%= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' } %></td>
The instance variable #categories should be defined in CategoriesController, which is a subclass of action controller. Ruby's instance variables are not persistent, and any #variables you defined in a controller action is accessible in the action's view. I am not sure if you are familiar with MVC patterns, and if not, you can take a look at this question:
What is MVC in Ruby on Rails?
Name is an attribute of the resource/model category. You should see its class in app/model/category.rb. It is a subclass of ActiveRecord, which acts as a wrapper of the database of your choice. So you probably have a database table called categories with column name 'name'.
And as #JoelL mentioned, the link_to are view helpers that are meant to simplify your syntax in view files,make your code more organized, and save you time. You can define your own view helpers in app/helpers. Some of the helpers are automatically made for you when you define a resources :resource_name in config/routes.rb. In this case, you probably have resources :categories in your config/routes.rb
I'm new to RoR, so please be gentile. I'm not sure, if I search for the right topic. However, I've spent the whole day trying to figure out, how to work with the has_man, belongs_to and so forth asset associations.
Right now I have two assets:
sqlite> pragma table_info(meetups);
0|id|INTEGER|1||1
1|name|varchar(255)|0||0
2|owner|integer|0||0
3|dateOfInception|datetime|0||0
4|homeTown|varchar(255)|0||0
5|created_at|datetime|0||0
6|updated_at|datetime|0||0
7|activity_id|integer|0||0
sqlite> pragma table_info(activities);
0|id|INTEGER|1||1
1|name|varchar(255)|0||0
2|location|varchar(255)|0||0
3|startDate|datetime|0||0
4|duration|integer|0||0
5|description|varchar(255)|0||0
6|created_at|datetime|0||0
7|updated_at|datetime|0||0
8|image|varchar(255)|0||0
9|meetup_id|integer|0||0
So I can create a new meetup and select multiple saved activities. For every meetup we can select a multiple activities. If I create a meetup, they corresponding activities are also stored correctly, as you can see in the image below:
Image
However, it's not useful to output them just like an array. It would be great, if the activity name would appear. But how is that possible? I tried so many things, renaming the db foreign keys, create a find method in the meetup controller... but nothing worked. Please help me out here - I think I'm very near but someting I dont know doesnt work.
<% #meetups.each do |meetup| %>
<tr>
<td><%= meetup.name %></td>
<td><%= meetup.owner %></td>
<td><%= meetup.dateOfInception %></td>
<td><%= meetup.homeTown %></td>
<td><%= meetup.activity_ids %></td>
<td><%= link_to 'Show', meetup %></td>
<td><%= link_to 'Edit', edit_meetup_path(meetup) %></td>
<td><%= link_to 'Destroy', meetup, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
class MeetupsController < ApplicationController
before_action :set_meetup, only: [:show, :edit, :update, :destroy]
# GET /meetups
# GET /meetups.json
def index
#meetups = Meetup.all
end
Many thanks for your help!
Try this in your view:
meetup.activities.map(&:name).join(',')
That should show the data you want. For performance reasons, you'll want to add .include(:activities) to
the controller action that loads your list of meetups.
It sounds like you're trying to model a Has And Belongs To Many relationship, though? You'll need a third table to model that correctly.
If that's not what you're wanting to model, you should remove the activity_id column from the meetups table.
Hello I want to make simple shopping cart. I am a beginner in programming. So please help. I have items with prices and quantities. I want to place button "Plus One", so when i press it should add one to quantity.
<td><%= item.name %></td>
<td><%= item.price %></td>
<td><%= item.quantity %></td>
<td><%= link_to 'Show', item %></td>
<td><%= link_to 'Edit', edit_item_path(item) %></td>
<td><%= link_to 'Destroy', item, :confirm => 'Are you sure?', :method => :delete %></td>
<td><%= link_to "Plusone" %></td>
Innocent suggestion. Buy a copy of Agile Web Development with Rails 4th Ed If I remember correctly this is the same example solved there through out the book. And it worth buying.
To be frank, this is kind of a difficult problem for a beginner. If you want a button that does nothing but add one to the quantity, you're talking about defining a custom action, so you need to read up on Rails routes. Here's a good Railscast addressing this. There's also a follow-up episode.
Next, if you want this to dynamically update a field on the page without reloading, you're talking about an AJAX call to your custom action. Here's a Railscast for Rails 2, and here's a Railscast for Rails 3. These should have the information you need to make an AJAX call to your controller action and handle the response, either with a success handler or a js.erb template.
In addition to the sources mentioned above, other useful sources are: Ruby on rails guides, 'Head first rails' book:)