How to display paperclip's uploads. - ruby-on-rails

Im currently building a blog. While the paperclip photos pop up inside the individual blog posts they don't seem to pop up in the index, where all the blog posts are displayed.
13th line seems to be the problem.
this is my index.html.erb for my posts
10 <% #posts.each do |post| %>
11 <tr>
12 <td><%= link_to post.title, post_path(post) %></td>
13 <td><%= image_tag #post.picture(:medium) %></td>
14 <td><%= post.text %></td>
15 <td><%= link_to 'Show', action: :show, id: post.id %></td>
16 <td><%= link_to 'Edit', action: :edit, id: post.id %></td>
17 <td><%= link_to 'Destroy', { action: :destroy, id: post.id },
18 method: :delete, data: { confirm: 'Are you sure?' } %></td>
it throws me a no method error.
Please let me know if I can give you extra files if you need more information
Thank you in advance!

You're not passing the URL for the image to the image_tag helper.
You need to display your image like this:
<%= image_tag post.picture.url(:medium) %>

You're trying to access the #post instance variable, but that instance variable doesn't exist. Rather, within your loop, you should access your post local variable as such:
<%= image_tag post.picture.url(:medium) %>
Note also that, from the documentation, the correct syntax to access variations of a Picture instance involves passing the variation name to the url attribute:
post.picture(:medium) # Invalid
post.picture.url(:medium) # Valid!

As mentioned by Jon, you need to use the .url method on your picture object (official documentation):
<%= image_tag post.picture.url(:medium) %>
Paperclip
The reason for this is Paperclip actually creates its own picture object & attaches several methods to that (url being one of them). This means you have to call url each time you show the post's image to get it to load
Normally, you'd be able to call methods on your instance or local variables, but as Paperclip actually creates its own object, you have to use its in-built methods to get it to work correctly

Related

Rails turn URL string into hyperlink

So I'm iterating over a table to kick out link title and link urls for each additional item thats being added by a user. Ultimately I want a very basic:
Title, URL
I need the URL to be clickable and I'm hitting a wall.
<tbody>
<% #links.each do |link| %>
<tr>
<td><%= link_to link.url %></td>
<td><%= link.title %></td>
<td><%= link_to 'Show', link %></td>
<td><%= link_to 'Edit', edit_link_path(link) %></td>
<td><%= link_to 'Destroy', link, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
Right now the link_to link.url will display the correct link but the link redirects back to the homepage. I've also tried:
url_to link.url
error message that says "did you mean url_for"
url_for link.url
which removes a hyperlink
link_to("#{link.url}")
which has the same issue my code above in that it links back home
link_to("#{#link.url}")
which returns an error of: undefined method `url' for nil:NilClass
link_url("#{link.url}")
returns the entire localhost address and then the link...not a hyperlink
auto_link(link.url)
returns an error asking if I meant autoload
Surely I'm missing something that's super easy.
for your reference link_to
the format is
link_to(body, url, html_options = {})
# url is a String; you can use URL helpers like
for your problem
<td><%= link_to link.url, "http://#{link.url}" %></td>

Shuffling an array in ruby on rails [duplicate]

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)

Rails resources routes miss parameters yet match documentation

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.

How to delete association with parent controller update action? Rails

I'm using Rails 4
I need to delete association Box with link_to method. The problem is that I have to do it from parrent controller and method: patch. my corrent code is doing nothing because I don't know how to use data: for link_to.
#views/modifications/show.html.erb
<% #modification.boxes.each do |box| %>
<tr>
<td><%= box.name %></td>
<td><%= link_to "delete", #modification, remote: true, method: :patch %></td>
</tr>
<% end %>
By the way, this is used with Ajax so page doesn't need to be reloaded.
I have to do it
You don't have to do anything in any way - if Microsoft can release Windows for all the PC's in the world, I'm sure you can get this working.
You have several issues, the most important of which being... how do you identify the box object to delete?
The whole point of nested resources (which is what you need) is to give you the ability to identify a "parent" object and a child object.
Your current setup prevents you from identifying the box you wish to remove. Ideally, you should use the following code to get it sorted:
#config/routes.rb
resources :modifications do
resources :boxes, only: :destroy
end
#app/views/modifications/show.html.erb
<% #modification.boxes.each do |box| %>
<tr>
<td><%= box.name %></td>
<td><%= link_to "delete", [#modification, box], remote: true, method: :delete %></td>
</tr>
<% end %>
#app/controllers/boxes_controller.rb
class BoxesController < ApplicationController
def destroy
#modification = Modification.find params[:modification_id]
#box = #modification.boxes.find params[:id]
#box.destroy
end
end
Try to using link_to with delete method on box destroy path, like this:
<%= link_to 'Delete', box_path(box), method: :delete, remote: true %>

Ruby on Rails - Unable to Display Associated Item From Database (#<Comment:0x44f9ec8>)

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

Resources