从视图中的模型方法返回多个值

时间:2013-03-26 02:30:59

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我的模型中有以下方法:

  def self.set_bad_recommedation_size(rating_set)
    bad = Rating.where(rating_set: rating_set).where(label: 'Bad').count
    total = Rating.where(rating_set: rating_set).count
    percentage_bad = (bad.to_f/total.to_f * 100)
    return bad, total, percentage_bad
  end

如何在视图中调用变量bad,total,percentage_bad。 我想要的是什么:

<%= "#{Model.set_bad_recommedation_size(rating_set).bad}/#{Model.set_bad_recommedation_size(rating_set).total"%>

2 个答案:

答案 0 :(得分:1)

你最好这样做:

<% bad, total, percentage_bad = Model.set_bad_recommedation_size(rating_set) %>
<%= "#{bad}/#{total}" %>

这样你就不会多次调用这个方法了。

答案 1 :(得分:1)

我会添加一个中间帮助器,以便您的视图更好地显示

<%= bad_recommendation_ratio(result_set) %>

Application.helper

def bad_recommendation_ratio(result_set)
  bad, total = Model.set_bad_recommedation_size(rating_set)
  "#{bad}/#{total}"
end