从数组rails中选择特定属性

时间:2013-08-20 16:49:55

标签: ruby-on-rails arrays

我有帖子模型

class Post < ActiveRecord::Base
     acts_as_voteable
 end 

和投票模型

class Vote < ActiveRecord::Base

 scope :for_voter, lambda { |*args| where(["voter_id = ? AND voter_type = ?", args.first.id, args.first.class.name]) }
  scope :for_voteable, lambda { |*args| where(["voteable_id = ? AND voteable_type = ?", args.first.id, args.first.class.name]) }
 scope :recent, lambda { |*args| where(["created_at > ?", (args.first || 2.weeks.ago)]) }
 scope :descending, order("created_at DESC")

  belongs_to :voteable, :counter_cache=>true,:polymorphic => true,:touch=>true
   belongs_to :voter, :polymorphic => true

  attr_accessible :vote, :voter, :voteable


 # Comment out the line below to allow multiple votes per user.
 validates_uniqueness_of :voteable_id, :scope => [:voteable_type, :voter_type, :voter_id]

end

当我用这些方法获得选民时

  <% @post.voters_who_voted.each do |voter|%>
  <%= voter.name %>
   <% end %>

我加载了我的数据库 如何从这些数组中仅选择用户名和用户ID?

更新我更改了我的代码我正在使用thumbs_up gem我先粘贴较少的代码来简化问题

2 个答案:

答案 0 :(得分:1)

“load database”是什么意思?如果您只想选择ID和name列,请使用@post.users.select([:id, :name]).each ...

或者它是关于this problem(根据您提供的代码)?

UPD。

voters_who_voted加载所有选民并返回数组https://github.com/bouchard/thumbs_up/blob/master/lib/acts_as_voteable.rb#L113。您必须将自己的关联添加到Post模型:

has_many :voters, :through => :votes, :source => :voter, :source_type => 'User'

这只是一个例子,也许voters会与已有的方法冲突,如果有的话。

然后在此处使用它而不是voters_who_voted

答案 1 :(得分:1)

你尝试过收集方法吗?

names = @post.users.collect(&:name)

ids = @post.user.collect(&:id)

如果你想要它是相关的,你可以用它做一个HASH。 Id已映射到名称。

相关问题