2012-11-01 74 views
0

我在軌道上的新,我試圖讓我自己簡單的投票程序。我有兩個型號:has_may進行投票應用程序

class Product < ActiveRecord::Base 
    attr_accessible :description, :title, :photo 
    has_many :votes 

    has_attached_file :photo, :styles => { :medium => "300x300" } 

    before_save { |product| product.title = title.titlecase } 

    validates :title, presence: true, uniqueness: { case_sensitive: false } 
    validates :photo, :attachment_presence => true 

end 


class Vote < ActiveRecord::Base 
    belongs_to :product 
    attr_accessible :user_id 
end 

這裏是產品控制器

class ProductsController < ApplicationController 

    http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index] 

    def index 
     @products = Product.all 
    end 

    def indexprv 
     @products = Product.all 
    end 

    def show 
     @product = Product.find(params[:id]) 
    end 

    def edit 
     @product = Product.find(params[:id]) 
    end 

    def new 
     @product = Product.new 
    end 

    def create 
     @product = Product.new(params[:product]) 
     if @product.save 
      redirect_to @product 
     else 
      render 'new' 
     end 
    end 

    def update 
    @product = Product.find(params[:id]) 
    if @product.update_attributes(params[:product]) 
     flash[:success] = "Producto Actualizado" 
     redirect_to root_path 
    else 
     render 'edit' 
    end 
    end 

    def destroy 
    Product.find(params[:id]).destroy 
    flash[:success] = "Producto Eliminado." 
    redirect_to root_path 
    end 

end 

我有很多問題。

我怎麼能顯示每個產品總票數的產品我的索引頁?

我如何我的指數產品頁面添加一個投票的產品上創建按鈕?

我不知道如何做到這一點,我無法找到一個類似的例子任何教程Ø博客。

感謝您的幫助。

回答

1

你的索引視圖可能已經通過你的每一件產品循環(或者由部分或由循環)。在你的循環/分這樣做:(假設變量產品具有產品的實例)

product.votes.count 

拿到票的數量。爲了得到一個按鈕來添加一個投票做線沿線的東西:

link_to "Add Vote", new_product_vote_path(product), action: :new 

一個很好的教程,涵蓋軌道的許多方面是:http://ruby.railstutorial.org/chapters/beginning#top

編輯:

你在你的控制器指數法爲您提供您擁有的每一款產品。所以,如果你做這樣的事情在你的索引視圖(如果你使用ERB):

<ul> 
<% @products.each do |product| %> 
<li> 
    <%= product.title %>: <br /> 
    Votes: <%= product.votes.count %> <br /> 
    <%= link_to "Add Vote", new_product_vote_path(product), action: :new %> 
</li> 
<% end %> 
</ul> 

它應該做你想要什麼

+0

謝謝伊恩Armit但是當我嘗試這個product.votes.count我得到NoM​​ethodError :未定義的方法'投票'零:NilClass,我不明白爲什麼 – Jean

+0

變量產品需要分配產品的一個實例,如果你發佈你的控制器和索引視圖代碼,它會幫助。 –

+0

準備好了,我剛發佈的產品控制器 – Jean