簡體   English   中英

如何在Rails中實施投票?

[英]How to implement voting in Rails?

我在chapter 10Michael Hartl上的RailsTutorial上,做了一些額外的工作,為每個RailsTutorial添加了回形針圖像。 當我向Micropost添加照片時,我稱它為Microphoto
現在,我做了以下工作:

  1. 正確遷移數據庫

     class CreateMicrophotos < ActiveRecord::Migration def change create_table :microphotos do |t| t.string :content t.integer :user_id t.integer :votes_up t.integer :votes_down t.timestamps end add_index :microphotos, [:user_id, :created_at] end end 
  2. 更改顯微照片模型和控制器

  3. 寫一些觀點

這是我的文件:

用戶模型

class User < ActiveRecord::Base
  require "paperclip" 
  attr_accessible :name, :email, :password, :password_confirmation, :avatar,
:avatar_file_name, :avatar_content_type, :avatar_file_size, :avatar_updated_at
  has_secure_password
  has_many :microphotos, dependent: :destroy
  has_attached_file :avatar, :styles => { :large => "120x120>", :medium => "48x48>", :thumb => "26x26>" }
  .
  .
  .
  def feed
    Microphoto
  end
end

顯微照片模型

class Microphoto < ActiveRecord::Base
  attr_accessible :content, :votes_down, :votes_up, :photoclip,
  :photoclip_file_name, :photoclip_content_type, :photoclip_file_size, :photoclip_updated_at
  belongs_to :user
  has_attached_file :photoclip, :styles => { :large => "500x400>", :medium => "100x80>" }
  validates :content, presence: true, length: { maximum: 140 }  
  validates :user_id, presence: true
  default_scope order: 'microphotos.created_at DESC'
end

Microphotos控制器

class MicrophotosController < ApplicationController
  before_filter :signed_in_user, only: [:create, :destroy]
  def index
  end
  def create
    @microphoto = current_user.microphotos.build(params[:microphoto])
    if @microphoto.save
      flash[:success] = "Your photo has been uploaded successfully!"
      redirect_to root_url
    else
      render 'static_pages/home'
    end
  end
  def destroy
  end
end

我希望發生一件事:

  • 登錄的用戶可以從其他用戶投票給Microphotos,但不能投票給其他人

    我該怎么辦?

我試圖更改microphotos控制器更改操作。 我知道這可能不是一個真正的問題,但是由於我是Rails的新手,所以我不能這樣做。

[更新1]

我使用anonymousxxx建議的方法,但最終導致出現此路由錯誤消息:

沒有路線匹配{:controller =>“ microphotos”,:action =>“ vote_up”,:id =>#}

使用命令rake routes我有這個:

        users GET    /users(.:format)           users#index
              POST   /users(.:format)           users#create
     new_user GET    /users/new(.:format)       users#new
    edit_user GET    /users/:id/edit(.:format)  users#edit
         user GET    /users/:id(.:format)       users#show
              PUT    /users/:id(.:format)       users#update
              DELETE /users/:id(.:format)       users#destroy
     sessions POST   /sessions(.:format)        sessions#create
  new_session GET    /sessions/new(.:format)    sessions#new
      session DELETE /sessions/:id(.:format)    sessions#destroy
  microphotos POST   /microphotos(.:format)     microphotos#create
   microphoto DELETE /microphotos/:id(.:format) microphotos#destroy
         root        /                          static_pages#home
       signup        /signup(.:format)          users#new
       signin        /signin(.:format)          sessions#new
      signout DELETE /signout(.:format)         sessions#destroy
         help        /help(.:format)            static_pages#help
        about        /about(.:format)           static_pages#about
        terms        /terms(.:format)           static_pages#terms
      vote_up PUT    /vote_up/:id(.:format)     microphotos#vote_up
    vote_down PUT    /vote_down/:id(.:format)   microphotos#vote_down

[更新2]

經過他的指示,我得到了這個ArgumentError
can't use collection outside resource(s) scope

config/routes.rb:18:in `block (3 levels) in <top (required)>'
config/routes.rb:17:in `block (2 levels) in <top (required)>'
config/routes.rb:16:in `block in <top (required)>'
config/routes.rb:1:in `<top (required)>'

這是routes.rb

16  resources :microphotos do
17    collection do
18      put '/vote_up/:id' => "microphotos#vote_up", :on => collection, :as => :vote_up
19      put '/vote_down/:id' => "microphotos#vote_down", :on => collection, :as => :vote_down
20    end
21  end

您可以使用act_as_votable gem。

安裝gem:

gem 'acts_as_votable', '~> 0.5.0'
bundle

安裝和運行遷移:

rails generate acts_as_votable:migration
bundle exec rake db:migrate

Microphoto模型中,您應該具有:

acts_as_votable

完成此操作后,您可以使用以下方法來投票/撤消microphotos

@microphoto.liked_by @user1
@microphoto.downvote_from @user2
@microphoto.vote :voter => @user3
@microphoto.vote :voter => @user4, :vote => 'bad'
@microphoto.vote :voter => @user5, :vote => 'like'

考慮一下act_as_rateable gem,它可能比Marek Lipka建議的適合您的特定用例更適合您。

解決方案1(用戶可以多次投票)

您可以在顯微照片上使用if.. else..語句。

參見清單10.46 將刪除鏈接添加到微博部分。

微型帖子只能由所有者用戶刪除。

<% if current_user?(micropost.user) %>
    <%= link_to "delete", micropost, method: :delete,
                                     data: { confirm: "You sure?" },
                                     title: micropost.content %>
  <% end %>

示例(未經測試,但希望能對您有所幫助):

  # on view (e.g show.html.erb)

  <% if signed_in? && current_user.id != feed_item.user_id %>
    <%= link_to "vote up", vote_up_microphotos_url(feed_item.id), :method => :put %> 
    <%= link_to "vote down", vote_down_microphotos_url(feed_item.id), :method => :put %>
  <% end %>


  # controller
  before_filter :signed_in_user, only: [:create, :destroy, :vote_up, :vote_down]


  def vote_up
    @microphoto = Microphoto.find(params[:id])
    @microphoto.update_attribute(:votes_up, @microphoto.votes_up + 1)
    redirect_to root_path
  end

  def vote_down
    @microphoto = Microphoto.find(params[:id])
    @microphoto.update_attribute(:votes_down, @microphoto.votes_down + 1)
    redirect_to root_path
  end

  # route
  resources :microphotos do
    collection do
     put '/vote_up/:id' => "microphotos#vote_up", :as => :vote_up
     put '/vote_down/:id' => "microphotos#vote_down", :as => :vote_down
    end
  end

解決方案2(用戶不能多次投票)

如果你想用戶無法在顯微照片多票,你應該有一個單獨的模型microphoto model的選舉權和vote model具有與關系microphoto model ,關系是這樣的:

class User < ActiveRecord::Base
has_many :vote_photos
has_many :microphotos
end

class Microphoto < ActiveRecord::Base
has_many :vote_photos
belongs_to :user
end

class VotePhoto < ActiveRecord::Base
 belongs_to :microphoto
 belongs_to :user
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM