【问题标题】:Rails: list of pins that a user upvotedRails:用户投票的 pin 列表
【发布时间】:2014-07-08 11:22:34
【问题描述】:

我有一个带有基本设置的 rails 应用程序,允许用户对 pin 进行投票,这些 pin 的顺序是从最多投票到较少投票。我现在想做的是呈现用户在其个人资料上点赞的 pin 列表。

这是我的配置:

app/controllers/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

app/models/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

app/models/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

app/models/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

你有什么想法吗?

【问题讨论】:

  • 你想查询得到用户投票的pin列表吗?
  • @lcicle 是的,然后我希望用户投票赞成的图钉显示在他的个人资料中。你明白我的意思吗?

标签: ruby-on-rails ruby devise


【解决方案1】:

例如,您可以通过以下方式获得用户@user 支持的图钉:

@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 %>

【讨论】:

  • 感谢您的回答我用您的解决方案更新了我的代码,但我遇到了一个错误:未定义的局部变量或方法 `pins_for_user' for #:0x007fc357474150>
  • 你在哪里运行这个错误(哪个类)?哦,对不起,我忘了在视图代码中添加@。我会更新这个。
  • 当我尝试在 app/views/users/show.html.erb 访问用户个人资料时
  • 哦,抱歉,我忘了在视图代码中添加@,它现在应该可以工作了,但是当然你必须用你的属性更新 -code有别针和你的显示方式。
  • 哦,我怎么没注意到!谢谢艾琳!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
相关资源
最近更新 更多