Method calling helper method response - ruby-on-rails

I have a method in my helper that returns rows of results. I want to pass this to a method in my model which is called by another method.
Helper Method:
def transactions(account_id, start, finish)
response = get_call('/Accounts/Statements/' + account_id.to_s + '/' + start + '/' + finish)
response = JSON.parse(response.body)
#transactions = response.map {|txn| Transaction.new(txn)}
return #transactions
end
Model Method I wish to call helper method into:
def transaction
??
end
Model Method which requires the transaction method:
def to_pdf
title = #account.name
subtitle = "Account Statement: #{#month_name} #{#year}"
StatementPDF.new(title, subtitle, #transactions).render
end
In the initialise section of this method i have added:
#transactions = {}
The Prawn PDF is now being generated but without the rows of results. Let me know if any other information is required.

You can reference your helpers from models using ApplicationController.helpers method:
ApplicationController.helpers.transactions(...)
This will solve your problem but, in my opinion, it would be much better, if you refactor your code and don't use helpers from model.

Related

ROR: Creating a method with a parameter

I have an admins dashboard which displays posts created in the last 24 hours, 7 days, 28 days etc.
def index
#1DayPosts = Post.where(created_at: 1.days.ago..DateTime.now).count
#7DaysPosts = Post.where(created_at: 7.days.ago..DateTime.now).count
#28DaysPosts = Post.where(created_at: 28.days.ago..DateTime.now).count
end
How could I make this into one line? Something like the below:
def index
#calculatePosts(a) = Post.where(created_at: a.days.ago..DateTime.now).count
end
Then in the view I could do:
=#calculatePosts(1)
Or would I need to create a new method?
def calculatePosts(a)
#calculatePost = Post.where(created_at: a.days.ago..DateTime.now).count
end
How would I then call this in the index view?
Your best bet would be to create a scope on the Post model.
class Post ...
scope :last_x_days, -> (x) { where(created_at: x.days.ago..Time.zone.now) }
end
Then you can call that anywhere really, in your view or controller like this.
#last_10_days = Post.last_x_days(10).count
EDIT:
You could do this also, but scopes are meant to be chain-able, so this is discouraged, though not wrong.
scope :last_x_days_count, -> (x) { where(created_at: x.days.ago..Time.zone.now).count }

Wrong number of arguments (2 for 3)

it is the first time to encounter this error in rails and i really don't know where is it coming from here is the function implementation :
def self.send (sender,recivers,content)
recivers.each do |reciver|
#notification = Notification.new
#notification.sender= sender
#notification.user = reciver
#notification.body = content
#notification.save
end
end
and here is how am calling it :
def after_create(announcment)
instructor_id = announcment.course.instructor_id
sender = User.find_by_id(instructor_id)
students = announcment.course.users
body = announcment.announcment
coures_name = announcment.course.name
Notification.send(sender,students,body)
UserMailer.notify_students_course(students,coures_name)
end
send is a Ruby method from Object class (so every class inherits it) that calls the method named with first argument and parameters the rest of the arguments given to send. Also in RoR its a reserverd word.
Better not overriding it, because it can get messy.

Filter controller result based on params

I'm trying to filter the results that are returned from my index view based on optional params. My code is working for the first param, sinceDate. But for the second param, searchQeury, nothing is filtered out.
_controller.rb
def index
since = params[:sinceDate]
query = params[:searchQuery]
#articles = Comfy::Cms::Page.published.all
if since
#articles = #articles.reject{ |a| a[:created_at] < Date.parse(since) }
end
if query
#article = #articles.select{ |a| a[:label].match(/#{query}/i) }
end
end
Is it possible that the problem is a typo?
In the line after "if query", it should be perhaps #articles instead of #article.

Grails redirect breaks params types

My Grails code has a search function that redirects to another controller action after performing a findAllBy query:
def results = Foo.findAllByBar(baz)
redirect(action: "result", params: [results: results])
findAllByBar returns an ArrayList with models, as expected, but after the redirect the receiving action gets a String array. Worse, when there is only one result it doesn't even get an array, it just gets a String.
Given that I have to iterate through the results in the receiving view, doing it on a string will meticulously print every letter individually. We can all agree that that's probably not the ideal behaviour.
A redirect results in a new GET request with the parameters in the querystring, e.g. /controller/result?foo=bar&baz=123 - you can't put objects there since it's just a string.
You could put the ids of the objects in the params and load them in the result action:
def action1 = {
def results = Foo.findAllByBar(baz)
redirect(action: "result", params: [resultIds: results.id.join(',')])
}
def result = {
def resultIds = params.resultIds.split(',')*.toLong()
def results = Foo.getAll(resultIds)
}
or put them in Flash scope:
def action1 = {
flash.results = Foo.findAllByBar(baz)
redirect(action: "result")
}
def result = {
def results = flash.results
}
It sounds like you want to use the chain method instead of the redirect method. Chain lets you pass a model as a parameter similar to render.
An example would be:
chain(action:'result',model:[results:results])
Heres a link for further information:
http://www.grails.org/doc/latest/ref/Controllers/chain.html

Using a method while looping through an array in ruby

I am using ruby-aaws to return Amazon Products and I want to enter them into my DB. I have created a model Amazonproduct and I have created a method get_amazon_data to return an array with all the product information. When i define the specific element in the array ( e.g. to_a[0] ) and then use ruby-aaws item_attributes method, it returns the name I am searching for and saves it to my DB. I am trying to iterate through the array and still have the item_attributes method work. When i don't define the element, i get this error: undefined method `item_attributes' for #Array:0x7f012cae2d68
Here is the code in my controller.
def create
#arr = Amazonproduct.get_amazon_data( :r ).to_a
#arr.each { |name|
#amazonproduct = Amazonproduct.new(params[:amazonproducts])
#amazonproduct.name = #arr.item_attributes.title.to_s
}
EDIT: Code in my model to see if that helps:
class Amazonproduct < ActiveRecord::Base
def self.get_amazon_data(r)
resp = Amazon::AWS.item_search('GourmetFood', { 'Keywords' => 'Coffee Maker' })
items = resp.item_search_response.items.item
end
end
Thanks for any help/advice.
I'm not familiar with the Amazon API, but I do observe that #arr is an array. Arrays do not usually have methods like item_attributes, so you probably lost track of which object was which somewhere in the coding process. It happens ;)
Try moving that .item_attributes call onto the object that supports that method. Maybe amazonproduct.get_amazon_data(:r), before its being turned into an array with to_a, has that method?
It's not quite clear to me what your classes are doing but to use #each, you can do something like
hash = {}
[['name', 'Macbook'], ['price', 1000]].each do |sub_array|
hash[sub_array[0]] = sub_array[1]
end
which gives you a hash like
{ 'name' => 'Macbook', 'price' => 1000 }
This hash may be easier to work with
#product = Product.new
#product.name = hash[:name]
....
EDIT
Try
def create
#arr = Amazonproduct.get_amazon_data( :r ).to_a
#arr.each do |aws_object|
#amazonproduct = Amazonproduct.new(params[:amazonproducts])
#amazonproduct.name = aws_object.item_attributes.title.to_s
end
end

Resources