开发者

Returning array from method in model in Ruby on Rails 3

开发者 https://www.devze.com 2023-02-05 23:47 出处:网络
I\'ve got a method that caclulates an amount of roylaties owed to an author. It works like this: calculate_royalty(object_开发者_JS百科id)

I've got a method that caclulates an amount of roylaties owed to an author.

It works like this:

calculate_royalty(object_开发者_JS百科id)

Right now, I'm using it in a view and looping through each individual author's products and spitting out a number. Like this:

<%= @author.products.each do |product| %>
  <%= @author.calculate_royalty(product.id) %>
<% end %>

Right now, that gives me a single number. What I've been trying to do is load all of those numbers into an array in my model so I can total them. I trid this:

def total_author_royalties
   products do |p|
    calculate_royalty(p.id)
   end
end

But the array just returns as a hash of the product objects for that author. I figured once I have the values in the array, I can use Array.inject to add them all up.


Well, if calculate_royalty just returns a number, then in your loop you are not assigning it to anything, it just returns and disappears. Try pushing each royalty into an array and summing them at the end like so:

def total_author_royalties
   royalties = []
   products.each do |p|
     royalties << calculate_royalty(p.id)
   end
   royalties.sum
end

or a more concise version:

def total_author_royalties
  products.map{|p| calculate_royalty(p.id)}.sum
end
0

精彩评论

暂无评论...
验证码 换一张
取 消