I have a pretty common helper method in my application helper:
module ApplicationHelper
def quid(num)
number_to_currency (num / 100.0), unit: "£"
end
end
But my applications keeps throwing an 'undefined method `/' for nil:NilClass' error.
If I print number_to_currency (num) it doesn't have an issue, it's only when I try to put an operator like / * - + that it gives this error.
This was working fine until today, and it's only in the product index view that I get the error.
I'm not sure what's wrong, can anyone help explain? I'm stumped!
UPDATE:
Here's the product index view code:
<% #products.each do |product| %>
<h3><%= product.title %></h3>
<div id="link_text"><%= link_to "See more", product %></div>
<%= image_tag(product.avatar.url(:medium)) %><br/>
<%= product.description %><br />
<%= quid product.price_in_pence %>
<% end %>
price_in_pence is an integer, but turning 100.00 into 100 doesn't help, so I don't think that's the issue, I think it is because num is returning nil for some reason.
The error comes, because the num variable is nil in some cases. number_to_currency(nil) works, because the helper is implemented like this:
def number_to_currency(number, options = {})
return unless number
...
end
source: http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_to_currency
You see, a nil doesn't hurt here, because it will instantly return.
Your function, however, tries to execute nil / 100.0 first. As the error states, the / method is not defined on nil.
You probably need some special nil treatment, or hunt the cases when nil is given to your helper.
Related
I'm trying to create a search form in my rails application. I've looked up various solutions but they make little sense to me.
I'm getting the following error when I run a search through a form in my rails app. Right now my concern (other than the error) is my instance variable #computers in my index action. I'm pretty sure it's not 'the rails way' to get a search done properly and would love some advice.
Error
undefined method `%' for #<Array:0x5780460>
Parameters after Search
http://localhost:3000/computers?utf8=%E2%9C%93&direction=&sort=&search=bob
Search Form
<%= form_tag computers_path, method: "get" do %>
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Go", name: nil, class: "btn btn-primary" %>
<% end %>
Call to Method
def index
#computers = Computer.where(school_id: current_user.school_id).search(params[:search]).category(params[:category]).order(sort_column + " " + sort_direction)
end
Method
def Computer.search(search)
if search
search = search.downcase
params = []
values = {}
column_names.each do |c|
params << "#{c} LIKE #{c.to_sym}"
values[c.to_sym] = search
end
params.join (' OR ')
where(params,values)
else
all
end
end
You've got the right idea, but invoking the .join method does not change the object on which it is called, it merely returns a string representation. You need to store the return in a variable, something like this: paramsStr = params.join(' OR '). Then simply pass paramsStr to the where clause.
Ultimately, that is what is causing your unidentified method % for Array .... error; this version of the where method is expecting the first parameter to be a string. Check out this documentation, the part about placeholder conditions.
Hope that helps.
I have a part file where I want to show all my products for a specific partner.
Here's the html.erb:
<% unless #products.nil? %>
<% #products.each do |prod|%>
<tr id="p_<%= prod.id%>">
<td><%= prod.name %></td>
<td><%= prod.price %></td>
<td><%= number_field_tag "product_qty_input[#{prod.id}]", get_offer_product_qty(#offer.id, prod.id),:min => 0, :max => 99 %></td>
<td>X</td>
</tr>
<% end %>
<% end %>
But I keep getting the error: undefined method `each' for "2,1":String
it says it's on this line: <% #products.each do |prod|%>
But I don't see the problem..
Here's my controller:
def select_products
#partner = Partner.find(params[:partner_id])
if params[:id] == "-1"
#offer = nil
else
#offer = Offer.find(params[:id])
end
#select_callback = url_for( #offer.nil? ? new_partner_offer_path(#partner) : [:edit, #partner, #offer] )
#products = #partner.active_products
#num_select = PRODS_PER_OFFER
respond_to do |format|
format.html { render :template => "products/select"}
end
end
You see I have #products = #partner.active_products method, but i changed that to see if it got there, and it's not, must be something before...
I would apreciate any help.
Thanks in advance
UPDATE
Here is the method active_products :
def active_products
self.products.where("active IS NOT NULL AND active = true")
end
It should be returning the object not string
What am I doing wrong?
Thanks #thesis
UPDATE 2
Guys, Thanks a lot for the help, and with the assistence of #thesis I figured it out.
It was actualy something that I haven't thought about before, and it wasn't describe here in the question.
My sessionkeeper helped me keep my form as I selected products in another page!
That was meesing it up!
Your problem is very simple. You have to fix your active_products method, as it returns String. In your case, string is "2,1" but you have to return collection of products, to iterate it with each method.
For additional help, please update your question and add active_products instance method from Partner model.
Do you really have products as numbers "2,1".
#partner.active_products should ideally return ActiveRecord::Relation, hence it should iterate objects of Product class.
Please go through http://guides.rubyonrails.org/
And before that, you may like to search for 'ruby philosophy' and 'rails philosophy'
So basically in my partial I have the following line of code
...
<%= " active" if current_user."#{prop_row}" == "repeat-x" %>
...
So I tried to pass in the following variables "prop_id", "prop_row" using:
<%= render :partial => "users/image_props/repeat", :prop_id => "mbr", :prop_row => "main_background_repeat" %>
I get the error
/Users/codyjames408/rails/moz/app/views/users/image_props/_repeat.html.erb:4: syntax error, unexpected tSTRING_BEG
...= ( " active" if current_user."#{prop_row}" == "repeat-x" );...
...
^
I think the errors because its appending a string instead of the row method. But I am pulling my hair trying to figure how to work around this.
I would love to turn this into a big helper method or something! I just don't know how...
If prop_row is a string, containing the name of an attribute, you ucan do this:
<%= " active" if current_user.attributes[prop_row] == "repeat-x" %>
Or use this:
<%= " active" if current_user.send(prop_row.to_sym) == "repeat-x" %>
I guess it's a simple question, but how can I replace nil values in generell in my views.
I want to avoid having something like
<% unless value == nil %>
<%= value %> Ohm
<% else %>
<p>-</p>
<% end %>
Where is the best place to handle this?
I generally put little formatters like this in a helper:
module ResistorsHelper
def format_resistance(resistance)
resistance.nil? ? content_tag(:p, '-') : "#{resistance} Ohm"
end
end
I'm writing my first custom rails validation, and would like to tag the offending class with an html "error" class if they return false - I can't quite figure out how to do it. Relevant validation code below - any help appreciated.
(If it makes a difference, I'm using jQuery)
validates_each :shop do |record, attr, value|
shopvar = record.shops.map{ |s| s.email.downcase.strip }
if shopvar.count != shopvar.uniq.count
record.errors.add(attr, 'has the same email address entered more than once')
#record.errors[attr] << "You have entered this shop in the form twice"
end
end
So in your form you'd have something like this for an input field
<%= form.text_field :title %>
Since errors is a hash you could use the "include?" method like so...
errors.include?(:title)
This tells you that there's something wrong with this field. Now all you need to do is style it.
Whack on a ternary operator asi...
<% css_class = errors.include?(:title) ? "highlight_error_class" : "no_problem_class" %>
<%= form.text_field :title, :class => css_class %>
Done.