0

私はレールが初めてで、独自の簡単な投票アプリケーションを作成しようとしています。私は2つのモデルを持っています:

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

たくさんの質問があります。

製品のインデックス ページに製品ごとの総投票数を表示するにはどうすればよいですか?

インデックス製品ページにボタンを作成して、製品への投票を追加するにはどうすればよいですか?

これを行う方法がわからず、同様の例を含むチュートリアルまたはブログが見つかりませんでした。

ご協力いただきありがとうございます。

4

1 に答える 1

1

あなたのインデックス ビューは、おそらく既にすべての製品を (部分的またはループによって) ループしています。ループ/部分的に次のようにします: (変数 product に製品のインスタンスがあると仮定します)

product.votes.count

票数を取得します。投票を追加するボタンを取得するには、次の行に沿って何かを行います。

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

Rails の多くの側面をカバーする優れたチュートリアルは、http: //ruby.railstutorial.org/chapters/beginning#topです。

編集:

コントローラーの index メソッドは、持っているすべての製品の配列を提供します。したがって、インデックス ビューで次のようなことを行うと (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>

それはあなたが望むことをするべきです

于 2012-11-01T14:53:27.550 に答える