"ActionView::Template::Error ( isn't precompiled)" raised on "image_tag nil" - ruby-on-rails-3.1

If I don't handle view correctly, Production environment show 500.
<%= image_tag post.user.image_url %>
This could be
<%= image_tag post.user.image_url if post.user && post.user.image_url %>
but I am little careless and forgot this issue several times.
How can I prevent this? How can I use <%= image_tag nil %> in production environment without raising 500?

image_tag must have a source, Rails can do nothing with it, but raise an exception.
You can write a helper like this:
module ApplicationHelper
def safe_image_tag(source, options = {})
source ||= "default.jpg"
image_tag(source, options)
end
end
or simply check for nil directly in a view. Anyway you have to do something to prevent an error.

Related

Only execute code in erb if variable exists?

Ruby newbie here who just started using Ruby with .erb templates and I'm having a problem with the code. I have a hangman game that's passing variables from the .rb file to the .erb file and everything was working fine until I tried to check it on initial load (no variables present) and it threw errors. So I figured I'd use defined? with an if statement to check if the variable exists and then execute the code if it does and ignore if doesn't. It works fine when I use:
<% if defined?bad_guesses %>
<%= bad_guesses %>
<% end %>
But the information I need is an array and when I try to use an .each or .times statement like this:
<% if defined?bad_guesses %>
<% bad_guesses.each do |i| %>
<%= i %>
<% end %>
<% end %>
I get:
NoMethodError at /
undefined method `each' for nil:NilClass
C:/Projects/hangman/views/index.erb in block in singleton class
<% bad_guesses.each do |i| %> hangman.rb in block in
erb :index, :locals => {:game_status => game_status, :bad_guesses => bad_guesses, :good_guesses => good_guesses, :word => word}
Any suggestions appreciated.
Also, is this even the proper way to do this? When you make an .erb template that uses variables passed in from a class in your .rb file, how do you ignore it until it exists to the template?
Passing variables using:
get '/' do
if params['make'] != nil
make = params['make'].to_i
game_status, bad_guesses, good_guesses, word = Hangman.get_word(make)
elsif params['guess'] != nil
guess = params['guess'].to_s
game_status, bad_guesses, good_guesses, word = Hangman.check_guess(guess)
end
erb :index, :locals => {:game_status => game_status, :bad_guesses => bad_guesses, :good_guesses => good_guesses, :word => word}
end
Looking at this:
<% if defined?bad_guesses %>
<% bad_guesses.each do |i| %>
<%= i %>
<% end %>
<% end %>
a few points:
defined?a is bad style; use defined?(bad_guesses) or defined? bad_guesses instead.
defined? checks if it's defined, so if you say foo = nil; defined? foo it will be true.
You could alternatively use this:
defined?(bad_guesses) && bad_guesses
On the other hand, undefined instance variables are nil by default:
# it shows undefined
defined? #non_existing_var
# but you can still check if it's truthy:
puts "found" if #non_existing_var
# it won't print anything
Similar to instance variables in this regard are hashes. The default value of an unknown key is nil.
The problem with instance variables is they are not scoped to the partial. Instead, I recommend sending your local variables as a nested hash:
locals: { data: { foo: "bar" } }
Then you can safely check for values which may not exist:
if data[:foo]
# this runs
elsif data[:non_existent]
# this doesnt run
end
For my purposes, the following syntax worked:
<% if some_var %>
<%= some_var %>
<% end %>
This block is rendered if some_var is not nil.

String will work but not symbols in Rails

To learn Rails, I am writing a simple guestbook app that does not use a database.
Anyway, this is what my view looks like:
views/guest_book_pages/home.html.erb
<h1>Guest Book</h1>
<%= #userinput %>
<%= form_for(:guestbook) do |f| %>
<%= f.label :input %>
<%= f.text_field :input %>
<%= f.submit "Sign" %>
<% end %>
And the controller looks like this:
controllers/guest_book_pages_controller.rb
class StaticPagesController < ApplicationController
def home
#userinput = params[:guestbook]["input"]
end
end
Whenever I change the "input" to a symbol :input, the application breaks and gives me a warning that says: undefined method `[]' for nil:NilClass
What is the reason for this? Why can't I use a symbol?
update: Now it won't even work with the string. What is going on?
update#2: It works with both symbols and string. The only problem is that it will not load the first time. If I can get the page to load, then either will work. How can I get the page to load?
Action use to be handle something, and render view.
when you inter home, the home action has be called, and no param posted now.
for your code, home action should just be empty, it just to render the home_page.
your handle code should move to some action like sign_in, whitch handle the form post and you can get the params.
The first time you load the page the params var is not set. It is only when you submit your form back that there are params
Try
#userinput = params[:guestbook]["input"] || ''
which will initialize the #userinput to an empty string if the params is not found
edit:
This will check if the params has the key guestbook first, then will either set the instance var userinput to an empty string or the value of [guestbook][input] if it exsists.
If all else fails, the instance var is initialized to an empty string to prevent an error in your view.
if params.has_key?(:guestbook)
#userinput = params[:guestbook]["input"] || ''
else
#userinput = ''
end

In carrierwave, using simple_fields_for, iterating on a symbol (:pictures), how do I find the symbol for the image URLs?

I have a _form which renders another form with simple_fields_for. Everything works fine except I can't figure out the symbol that holds the different URLs, I particularly want the thumb URL.
For example, picture.image_uploader_url — but I don't have the actual object, just the :pictures symbol which is being iterated on. So far :image_uploader_url.to_s doesn't give anything useful and I realized this is because that will always just give the symbol name.
Super form:
<%= simple_form_for(#project) do |f| %>
[...]
<%= f.simple_fields_for :pictures do |builder| %>
<%= render "pictures/form", f: builder %>
[...]
Sub form (pictures/_form):
<% unless [:image_uploader_url].nil? or [:image_uploader_url].empty? %>
<%= image_tag(:thumb_url.to_s) %>
<% end %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.input :image_uploader, as: :file %>
<%= f.hidden_field :image_uploader_cache %>
How do I know in general what symbols I will have access to and how do I use them? maybe I dont have them?
EDIT: I don't have 'picture' to work with, only ':pictures' which I'm struggling to find what all I can get from this (i.e. picture has an image_uploader which I can get image_uploader_url(:thumb) but I can't do this with symbols, nor do I know how to get the picture that is the current iteration).
To get the thumb url for picture, just do this: picture.thumb.url. To get the original url, picture.url would do fine.
As far as I could figure out there is no way to get to the individual pictures that are related to the :pictures symbol. I ended up just scrapping the symbol and passing local variables (I was trying to avoid having the controller from making more information directly available).
I still don't have a satisfactory answer but this is the best I could come up with.

How do I perform inline calculations on two variables within an .erb file?

I have the following .erb view in a Sinatra app:
<% sessions.each do |session| %>
<%= session.balance_beginning %>
<%= session.balance_ending %>
<% end %>
It works as expected, displaying the beginning and ending balances recorded for each session. I would like to calculate the net balances from within the .erb file, but I can't figure out how to do it. I have tried variations of this:
<% sessions.each do |session| %>
<%= session.balance_ending - session.balance_beginning %>
<% end %>
That doesn't work. I receive the following error in Sinatra:
undefined method `-' for nil:NilClass
How do I do what I'm trying to do?
Right #Zabba, in this case I think you would add a method to your Session model so you could call session.net_balance.
Then in your balance_ending and balance_beginning methods you would want to handle nil, either raise an error or return zero if that is valid.

How to upload a file temporarily in Rails 3?

I'm creating CSV-upload functionality for a site of mine.
I'm looking to upload a file, parse it, and then dispose of it.
I know I can upload and save a file using Paperclip, but that seems a bit like overkill.
All I need to do is parse the uploaded file and never save it.
How would I go about doing this in Rails 3?
Note: I'd prefer to do the uploading manually without using an external gem so I can learn how to process works, but any suggestions are welcome.
Thanks!
Use the file_field helper in your form, then in your controller you can use File.Write and File.read to save the file.
E.g. View
<%= form_for #ticket do |f| %>
<%= f.file_field :uploaded_file %>
<% end %>
Controller
def upload
uploaded = params[:ticket][:uploaded_file]
File.open(<insert_filename_here>, 'w') do |file|
file.write(uploaded.read)
end
end
Edit: Just saw #klochner's comment, that link says pretty much what I have said so follow that: RubyOnRails Guides: Uploading Files.
Paste this in your model
def parse_file
File.open(uploaded/file/path, 'w') do |f| # Feed path that user gives in some way
## Parse here
end
end
this in view
<%=form_for #page, :multipart => true do |f|%>
<ul><li><%= f.label :file%></li>
<li><%= f.file_field :uploaded_file%></li></ul>
<%end%>
Let me know if this works. If it fails figure out a way to feed path of uploaded_file in parse_file method (the definite way which will work is storing file location in db and picking up from there, but it is not the right way to do this thing). Otherwise, I guess it should work.
Complete Example
Take, for example, uploading an import file containing contacts. You don't need to store this import file, just process it and discard it.
Routes
routes.rb
resources :contacts do
collection do
get 'import/new', to: :new_import # import_new_contacts_path
post :import, on: :collection # import_contacts_path
end
end
Form
views/contacts/new_import.html.erb
<%= form_for #contacts, url: import_contacts_path, html: { multipart: true } do |f| %>
<%= f.file_field :import_file %>
<% end %>
Controller
controllers/contacts_controller.rb
def new_import
end
def import
begin
Contact.import( params[:contacts][:import_file] )
flash[:success] = "<strong>Contacts Imported!</strong>"
redirect_to contacts_path
rescue => exception
flash[:error] = "There was a problem importing that contacts file.<br>
<strong>#{exception.message}</strong><br>"
redirect_to import_new_contacts_path
end
end
Contact Model
models/contact.rb
def import import_file
File.foreach( import_file.path ).with_index do |line, index|
# Process each line.
# For any errors just raise an error with a message like this:
# raise "There is a duplicate in row #{index + 1}."
# And your controller will redirect the user and show a flash message.
end
end

Resources