Rails:用户投票的引脚列表

时间:2014-07-08 11:22:34

标签: ruby-on-rails ruby devise

我有一个带有基本设置的rails应用程序,允许用户使用upvote引脚,这些引脚从最受欢迎的订购到较少的upvoted订购。我现在要做的是渲染用户在他的个人资料上投票的引脚列表。

这是我的配置:

应用/控制器/ pins_controllers.rb

def upvote
  @pin = Pin.find(params[:id])

  if @pin.votes.create(user_id: current_user.id)
    flash[:notice] =  "Thank you for upvoting! You can upvote a startup only once."
    redirect_to(pins_path)
  else 
    flash[:notice] =  "You have already upvoted this!"
    redirect_to(pins_path)
  end
end

应用/模型/ pin.rb

class Pin < ActiveRecord::Base

    belongs_to :user

    has_many :votes, dependent: :destroy
    has_many :upvoted_users, through: :votes, source: :user

    has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
    has_attached_file :logo, :styles => { :medium => "300x300>", :thumb => "100x100>" }

    end

应用/模型/ user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :pins    
  has_many :votes, dependent: :destroy
  has_many :upvoted_pins, through: :votes, source: :pin

end

应用/模型/ vote.rb

class Vote < ActiveRecord::Base

belongs_to :user
belongs_to :pin, counter_cache: true
validates_uniqueness_of :pin_id, scope: :user_id

end

我的 routes.rb

 resources :pins do
  member do
    post 'upvote'
  end
end

你有什么想法我能做到吗?

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式获取用户@user upvoted的引脚:

@pins_for_user = [] 
@user.votes.each do |vote| 
  @pins_for_user << vote.pin 
end

您可以将其嵌入用户控制器中,例如在show方法中。 然后你可以在你的节目视图(show.html.erb)中引用@pins_for_user并通过以下方式显示它:

<% @pins_for_user.each do |pin| %>
  <%= pin.name %> # or any other code to display that special pin
<% end %>