2013-08-18 27 views
0

我是新來的鐵軌,我正在努力理解結構以及方法應該在哪裏以及如何實例化。我現在很困惑自己。如何創建一個方法軌道4

這很好地工作在一個視圖問題是,這是不服從的MCV規則。

 <% @showblog.showruns.group(:spec_vote).count.each do |spec,count| %> 
     Spec: <%=" #{spec}"%> Votes: <%=" #{count}" %> <br/> 
     <% end %> 

我的視圖應該是 <%= @ voted.inspect%>或相似。

與所有其他的東西在別的地方。 在某些情況下,視圖上出現的所有內容是{},它本身爲零或零。

我最新的嘗試:

class Voted < ActiveRecord::Base 
    def voted(spec,count) 
    @showblog = Showblog.find(params[:showblog_id]) 
    @voted = @showblog.showruns.group(:spec_vote).count.each do |spec,count| 
    " Spec:#{spec} Votes: #{count}" 
    end end end 

這有一個零。

我在不同的地方添加了這個功能來試試看看會出現什麼問題,但即使是「無方法錯誤」,我仍然不知道應該在哪裏看到它。
logger.error「--------(有些詞讓我知道文件名)-------#{@ showblog.inspect}」 我的應用程序在heroku.com上

class Showblog < ActiveRecord::Base (parent) has_many :showruns, dependent: :destroy end 
class Showrun < ActiveRecord::Base (child) belongs_to :showblog end 

兩個控制器都包含正常的CRUD並且正常工作。

+1

這不是真的清楚你的問題是什麼。許多時候以其他人可以理解的方式提問,實際上可以幫助你更好地理解自己的問題。 –

+0

看看這是否有意義。 http://stackoverflow.com/questions/18165948/using-a-method-within-model-calling-it-from-view/18166048#18166048 – scaryguy

+0

爲了更好地理解方法檢查我的答案http:// stackoverflow .com/questions/18225543/how-can-i-call-methods-within-controller-ror – Mattherick

回答

0

在模型和控制器中,最好不要在其中添加視圖邏輯。最好的方法是在視圖中使用助手。

在您的應用程序/傭工/ application_helper.rb或其他幫助程序文件

,在您看來添加此

def vote_spec(blog) 
    result = '' 
    blog.showruns.group(:spec_vote).count.each do |spec,count| 
    result << "Spec: #{spec} Votes: #{count} <br/>" 
    # or the other logic you want to add such as using a table or div 
    end 
    result.html_safe 
end 

<%= vote_spec(@showblog) %> 
+0

正是我想要實現的。謝謝。 – Angie