我无法弄清楚如何列出所有喜欢特定帖子的用户。目前我正在使用:
<span class="count"><%= dailypost.likes.count %></span>
这使我可以计算与该特定 POST 关联的所有 LIKES。但它没有列出实际用户。
我尝试使用它来列出所有喜欢该帖子的用户
<%= dailypost.likes %>
相反,我回来了:
[#<Like id: 360, dailypost_id: 306, user_id: 1, created_at: "2013-04-28 21:51:45", updated_at: "2013-04-28 21:51:45">,
#<Like id: 319, dailypost_id: 306, user_id: 104, created_at: "2013-04-28 19:27:35", updated_at: "2013-04-28 19:27:35">,
#<Like id: 314, dailypost_id: 306, user_id: 103, created_at: "2013-04-28 19:24:19", updated_at: "2013-04-28 19:24:19">]
有谁知道我如何提取用户列表或 USER_ID 的列表?
RAILS 新手请帮忙!!
楷模
class User < ActiveRecord::Base
has_many :likes, dependent: :destroy
has_many :dailyposts, dependent: :destroy
end
class Dailypost < ActiveRecord::Base
belongs_to :user
has_many :likes
end
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :dailypost
end
数据库
ActiveRecord::Schema.define(:version => 20130210095553) do
create_table "dailyposts", :force => true do |t|
t.string "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "likes", :force => true do |t|
t.integer "dailypost_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
意见
<span class="count"><%= dailypost.likes.count %></span>
<%= dailypost.likes %>
<span class="like">
<% if like = current_user.likes.find_by_dailypost_id(dailypost.id) %>
<%= form_for like, :html => { :method => :delete }, remote: true do |f| %>
<span title="Unlike!"><%= image_submit_tag "Superman1.png" %></span>
<% end %>
<% else %>
<%= form_for current_user.likes.build, remote: true do |f| %>
<div><%= f.hidden_field :dailypost_id, value: dailypost.id %></div>
<%= f.hidden_field :user_id %>
<span title="Like!"><%= image_submit_tag "Superman2.png" %></span>
<% end %>
<% end %>
</span>