How to fix error in rails 7 action view helper? - ruby-on-rails-3

I'm getting this error ("wrong number of arguments (given 1, expected 0)") in the following helper.
module PropertiesHelper
def property_thumbnail
img = property.photo.present? ? property.photo.thumb.url : "placeholder.png"
image_tag img, class: "property_thumb"
end
end

In your Property Controller
helper_method :property_thumbnail
def property_thumbnail
img = property.photo.present? ? property.photo.thumb.url : "placeholder.png"
image_tag img, class: "property_thumb"
end

Related

How to pass a singleton object to a partial in rails?

I have the following code in my controller
#current_chat = current_user.sent_messages
.where("created_at > ? and receiver_id = ?", current_user.current_sign_in_at, current_chat[:receiver_id].to_i)
.select("body, created_at").each { |message| message.instance_eval { def type; #type end; #type = 'sent' } }
And I'm passing the #current_chat object to a partial like so:
<%= render partial: 'shared/chat_form', locals: { messages: #current_chat } %>
But I'm getting the following error:
singleton can't be dumped
At the first line in ActiveSupport::MessageVerifier#generate
def generate(value)
data = ::Base64.strict_encode64(#serializer.dump(value))
"#{data}--#{generate_digest(data)}"
end
Any ideas on how to fix this?. Thanks in advance.
You can not use this
#serializer.dump(value)
This is causing the error. Read this link, its all about using singletons in ruby.
link

How to add new variable for flash message with Devise?

In my RoR app, I'm passing flash messages using "notice" and "alert".
But, when I'm trying to pass like flash["warning"], for example, I receive: undefined local variable or method warning'
What can I do to be able to create a flash message passing 'warning' value?
Code:
#app/controllers/users/passwords_controller.rb
class Users::PasswordsController < Devise::PasswordsController
def create
user = params["user"]
if User.find_by_email(user["email"]).nil?
set_flash_message(:testing, :email_not_found) if is_navigational_format?
redirect_to root_path
else
self.resource = resource_class.send_reset_password_instructions(user)
if successfully_sent?(resource)
respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name))
else
respond_with(resource)
end
end
end
protected
def after_sending_reset_password_instructions_path_for(resource_name)
root_path
end
end
#app/views/landing/index.html.erb
.
.
<h5><%= testing %></h5>
Any help? Thanks!
Try to use a symbol. flash[:warning] = "XYZ" for example.

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!

How can I troubleshoot this JSON method in DataTables gem?

I'm trying to implement the Railscast 340 that demos how to use DataTables, which looks like an awesome gem for my project.
My model is different, of course; but the datatables class the Mr Bates builds (very quickly), in order to do server-side processing, is rather complicated to follow. I got the source code, and basically attempted to follow along. My view comes up with zero records (but there are > 10,000 records), but does not break.
However, here is what the error message output from the rails server says just before it stops:
NameError (undefined local variable or method `genotypes' for #<GenotypesDatatable:0xa9e852c>):
app/datatables/genotypes_datatable.rb:12:in `as_json'
app/controllers/genotypes_controller.rb:8:in `block (2 levels) in index'
app/controllers/genotypes_controller.rb:6:in `index'
Just before this, there appears to be this JSON error, which starts:
Started GET "/genotypes.json?sEcho=1&iColumns=8&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=...
The relevant part of the genotypes controller looks like this:
def index
respond_to do |format|
format.html
format.json { render json: GenotypesDatatable.new(view_context) }
end
end
And my genotypes model looks like:
class Genotype < ActiveRecord::Base
attr_accessible :allele1, :allele2, :run_date
belongs_to :gmarkers
belongs_to :gsamples
end
My datatables class is given below. This is from Mr Bates code, modified (most likely incorrectly) to replace his Products model with my Genotypes model:
class GenotypesDatatable
delegate :params, :h, :link_to, to: :#view
def initialize(view)
#view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Genotype.count,
iTotalDisplayRecords: genotypes.total_entries,
aaData: data
}
end
private
def data
genotypes.map do |genotype|
[
link_to(genotype.name, genotype),
h(genotype.category),
h(genotype.released_on.strftime("%B %e, %Y")),
genotype.run_date
]
end
end
def Genotypes
#Genotypes ||= fetch_Genotypes
end
def fetch_genotypes
genotypes = Genotype.order("#{sort_column} #{sort_direction}")
genotypes = genotypes.page(page).per_page(per_page)
if params[:sSearch].present?
genotypes = genotypes.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
end
genotypes
end
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
columns = %w[gmarker gsample allele1 allele2 run_date]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
Any hints on how to troubleshoot (or fix!) this error much appreciated! (Getting this working for my project would be awesome!)
TIA,
rixter
I'm not sure if this is it, but your class has a Genotype method with capital G, it should be all lowercase.

Nested content_tag throws undefined method `output_buffer=` in simple helper

I'm trying to create a simple view helper but as soon as I try nest a couple of content tags it will throw NoMethodError: undefined method `output_buffer=' for
def table_for(list, &proc)
t = Table.new
proc.call(t)
t.render_column(list)
end
class Table
include ActionView::Helpers::TagHelper
attr_accessor :columns, :block
def initialize
#columns = Array.new
end
def col(name)
#columns << name
end
def render_column(list)
content_tag :table do
list.each do |c|
content_tag :td, c
end
end
end
end
Any hints of what's wrong? I've also seen that there's a XmlBuilder is that one better for my purpose?
ActionView::Base has built into it the Context module, which provides the methods output_buffer() and output_buffer=().
So you can solve your problem either by having your class do:
include ActionView::Context
Or even more simply:
attr_accessor :output_buffer
I think there were some changes about this in 3.0, but in previous versions the trick was to pass self:
def table_for(list, &proc)
Table.new(self)
# ...
def initialize(binding)
#binding = binding
#...
def render_column
#binding.content_tag :table do
# ...
end
end
I'm not sure if this is still how it's done in rails 3.
Another thing to fix in ordere for the code to work is to save the output of the inner content_tag somewhere, as with each the content is generated and then discarded. One of the possible solutions:
def render_column(list)
#binding.content_tag :table do
list.inject "" do |out, c|
out << #binding.content_tag(:td, c)
end.html_safe
end
end
With help from Nested content_tag throws undefined method `output_buffer=` in simple helper I ended up with the following solution inspired by the API for Formtastic.
<%= table_for(#users) do |t| %>
<% t.col :name %>
<% t.col :email %>
<% t.col :test, :value => lambda { |u| u.email }, :th => 'Custom column name' %>
<% t.col :static, :value => 'static value' %>
<% end %>
Using the output_buffer directly and probably reinventing the wheel the code looks like
module ApplicationHelper
def table_for(list, &block)
table = Table.new(self)
block.call(table)
table.show(list)
end
class Column
include ActiveSupport::Inflector
attr_accessor :name, :options
def initialize(name, options = {})
#name = name
#options = options
end
def td_value(item)
value = options[:td]
if (value)
if (value.respond_to?('call'))
value.call(item)
else
value
end
else
item[name]
end
end
def th_value
options[:th] ||= humanize(name)
end
end
class Table
include ActionView::Helpers::TagHelper
attr_accessor :template, :columns
def initialize(temp)
#columns = Array.new
#template = temp
end
def col(name, options = {})
columns << Column.new(name, options)
end
def show(list)
template.content_tag(:table) do
template.output_buffer << template.content_tag(:tr) do
columns.collect do |c|
template.output_buffer << content_tag(:th, c.th_value)
end
end
list.collect do |item|
template.output_buffer << template.content_tag(:tr) do
columns.collect do |c|
template.output_buffer << template.content_tag(:td, c.td_value(item))
end
end
end
end
end
end
end