haml_tag not returning any string - haml

Hi I've tried to copy my old haml_tags and it seems either they are not working for Rails 3.1rc4 or i'm doing somethign wrong. Can anyone point me to the right direction?
def bonus_value_of(stat)
bonus = current_user.character.send("bonus_#{stat}".to_sym)
capture_haml do
haml_tag :span, :class => "positive" do
"+#{bonus}"
end
end
end
thats my code which i call with
= bonus_value_of(stat)
and all i get is a blank span with positive class but no content(not even the plus)
is this a bug?

Here's my version.
1.Your helper should be in controller's helper, not in module Haml::Helper like it was described in some article.
2.Change your helper to this:
def bonus_value_of(stat)
bonus = current_user.character.send("bonus_#{stat}".to_sym)
haml_tag :span, :class => "positive" do
haml_concat "+#{bonus}"
end
end
And then use it in your view like this:
- bonus_value_of(stat)

I just ran into this. I needed to pass my span text as the second value to haml_tag.
def bonus_value_of(stat)
bonus = current_user.character.send("bonus_#{stat}".to_sym)
capture_haml do
haml_tag :span, "+#{bonus}", :class => "positive"
end
end

Related

sunspot surely this can be done with some ruby magic?

I need to access my rails model instance from inside the searchable block as indicated below.
class Product
include MongoMapper::Document
include Sunspot::Rails::Searchable
key :field_names, Array
searchable do |ss|
self.field_names.each do |field|
ss.double field[:name] do
field[:value]
end
end
end
end
does anyone know how to do this via Sunspot ?
I have a field_names array on each product instance that is different per product so i need to access it.
Thanks a lot
Rick
you mean this?
def Foo
attr_accessible :id, :title
def fields
['something']
end
searchable do
integer :id
string :title
string :fields, :multiple => true do
self.fields
end
end
end
well inside there, you're inside a different evaluation context (Solr::DSL or something like that). That's to provide the ability to have those keywords like "integer, string". Looks like you're trying to evaluate dynamic attributes/filters .. .. so see my modified response (below)
you mean this?
def Foo
attr_accessible :id, :title
#fields_to_dynamically_add = ['title']
searchable do |s|
s.integer :id
s.string :title
#fields_to_dynamically_add.each do |f|
s.string f.to_sym
end
end
end
PS: have not added fields to searchable blocks dynamically every myself (although the above works)

rails if result in scope

I have a scope on my user model
I want to use this scope within a block on a view to display an option
my scope looks like this
scope :can_own_project, where('superuser = ? OR projectadmin = ?', true, true)
in my view I can achieve what I am looking to do by:
#stdprojectusers.each do |projectuser| %>
<% if (projectuser.superuser == true) || (projectuser.projectadmin == true) %>OPTION<%end%>`
what I would like to do is something like
<% if projectuser.can_own_project %> OPTION <% end %>
or
<% if projectuser == User.can_own_project %> OPTION <% end %>
any advise?
thanks
I don't think you want a scope. Scope's are applied to classes. If I'm reading you right, you are working with an instance. Is there a reason you can't simply define a method on that class?
class ProjectUser << ActiveRecord::Base
def can_own_project?
superuser == true || projectadmin == true
end
end
Note, I changed your method and appended a '?'. It's a habit of mine and isn't necessary, but I like the question form myself.
Your scope should work, but performance will (over time) take a major hit. What you'd want to do is:
<% if User.can_own_project.include?(projectuser) %> OPTION <% end %>
What I think you're looking for is a helper method...
module UserHelper
def does_user_own_project?(user)
user.superuser || user.projectadmin
end
end
Your view could then look like:
#stdprojectusers.each do |projectuser| %>
<% if does_user_own_project?(projectuser) %>OPTION<%end%>
If you'll want to use this outside the scope of this view, you could also make it an instance method on User:
class User < ActiveRecord::Base
def does_user_own_project?
self.superuser || self.projectadmin
end
end

Learning to Search in Rails

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.

Duplicating a record with associated images using Carrierwave

I have an app which you can store order/invoices in. I'm building a simple feature where you can duplicate invoices for my customers. I wrote this method in my Order.rb model which:
Takes the invoice, duplicates the associated lineitems, adds the new OrderID into them...and does the same for associated images.
def self.duplicate_it(invoice)
new_invoice = invoice.dup
new_invoice.save
invoice.lineitems.each do |l|
new_lineitem = l.dup
new_lineitem.order_id = new_invoice.id
new_lineitem.save
end
invoice.images.each do |i|
new_image = i.dup
new_image.order_id = new_invoice.id
new_image.save
end
return new_invoice
end
Unfortunately, you can't just .dup the image because there's all this associate expiration stuff since I'm storing images on S3. Is there a way to regenerate the image maybe using its image_url?
The error I get when running this is below. Which tells me not all the associated image information is dup'd correctly.
Showing /Users/bruceackerman/Dropbox/printavo/app/views/orders/_image-display.erb where line #3 raised:
undefined method `content_type' for nil:NilClass
Extracted source (around line #3):
1: <% #order.images.each do |image| %>
2: <% if image.image && image.image.file %>
3: <% if image.image.file.content_type == "application/pdf" %>
4: <%= link_to image_tag("/images/app/pdf.jpg",
5: :class => 'invoice-image'),
6: image.image_url,
i think you can do the following
invoice.images.each do |i|
new_image = new_invoice.images.new({ order_id: new_invoice.id })
new_image.image.download!(i.image_url)
new_image.store_image!
new_image.save!
end
This is actually how I did it for each lineitem on an order:
def self.duplicate_it(invoice)
new_invoice = invoice.dup :include => {:lineitems => :images} do |original, kopy|
kopy.image = original.image if kopy.is_a?(Image)
end
new_invoice.save!
return new_invoice
end
It is a bit late however this is my solution. I have had far too many problems with .download!
if #record.duplicable?
new_record = #record.dup
if new_record.save
#record.uploads.each do |upload|
new_image = new_record.uploads.new({ uploadable_id: new_record.id })
new_image.filename = Rails.root.join('public'+upload.filename_url).open
new_image.save!
end
end
Here is my upload.rb
class Upload < ActiveRecord::Base
belongs_to :uploadable, polymorphic: true
mount_uploader :filename, ImageUploader
end
Hope it helps!

Access a query in Ruby on Rails

I have in my controller this:
#itemsok = Search.where("first_item_id = ?", params["3"])
This is sopposed to be a query in the search table of the database asking for all the searches that have a first_item_id = 3 ...
Question 1 .- The syntax is I found it in http://guides.rubyonrails.org/active_record_querying.html but im not sure if im using it right?
Ok the question 2 is, I have this on the controller, is it ok to have querys in the controller?
In the view im printing the variable <%= #itemsok %> and all I get is a
ActiveRecord::Relation:0x007fd3d3e894d8
Any suggestions?
Thanks in advance.
ActiveRecord 3 lets you chain relations together so you can do something like this:
#itemsok = Search.where("first_item_id = ?", params["3"]).where("foo = ?", "bar")
The where() function returns an ActiveRecord::Relation. Generally this isn't a problem, since if you use the object it'll automatically run the query and return the results on the object so you'll get the database objects. AR doesn't run the query until it's actually needed.
Where will return a list of items (Array), so if you're just debugging, change your view to this:
<%= debug #itemsok.to_a %>
You seem to be constructing the query wrong way.
If you want to search for records with first_item_id = 3, you should do:
Search.where("first_item_id = ?", 3)
This will return an array of matching records, something you can't easily print with <%= #itemsok %>. You should iterate over the elements and print each one:
<% #itemsok.each do |item| %>
<%= item.name %>
<% end %>
I'd also suggest defining to_s method for the objects you want to print.
class Search
def to_s
name
end
end
Then you can simply print the object and to_s method will be automatically called for you:
<% #itemsok.each do |item| %>
<%= item %>
<% end %>
The right way to do is to define a namedscope in the model and then use it in the controller.
Something similar to this :
class Search < ActiveRecord::Base
named_scope:item_ok,lambda {|*args|{:conditions=>["item_id >= ?", args.first]}}
end
and then call the namedscope from the controller like this :
#itemsok = Search.item_ok(params[:value])