开发者

Searching within an associated array in ruby - rails 3

开发者 https://www.devze.com 2023-03-14 03:49 出处:网络
So lets say we have a Post model, a User model and a View model. When a user views a post, a new record is created in the Views table. The table links the user, the post, and the current time. Later

So lets say we have a Post model, a User model and a View model.

When a user views a post, a new record is created in the Views table. The table links the user, the post, and the current time. Later if that user goes back to view the post again, the record is updated with a new time. Pretty basic stuff.

Posts has_many views, and Users has_many views Views belongs to Posts and Users

In the index view of the Posts, I want to call the specific view for each post i.e.

<% @Posts.each do |post| %>

<%= post.name %><br/>
<%= post.views %> # This connects all of the views related to this post.
             开发者_JS百科     # How do I get the only one connected to this post and the current_user.id? 

    <% end %>

I feel like theres some simple way of accomplishing this that I'm totally forgetting


You could do something like

current_user.views.where(:post_id => post.id)
# this may work, not sure
current_user.views.where(:post => post) 

or

post.views.where(:user_id => current_user.id)
# this may work, not sure
post.views.where(:user => current_user)
0

精彩评论

暂无评论...
验证码 换一张
取 消