【问题标题】:Searching within an associated array in ruby - rails 3在 ruby​​ 中的关联数组中搜索 - rails 3
【发布时间】:2011-06-19 15:27:00
【问题描述】:

假设我们有一个 Post 模型、一个 User 模型和一个 View 模型。

当用户查看帖子时,会在 Views 表中创建一条新记录。该表链接用户、帖子和当前时间。稍后,如果该用户再次返回查看帖子,则记录会更新为新时间。很基本的东西。

帖子有_many视图,用户有_many视图 视图属于帖子和用户

在帖子的索引视图中,我想调用每个帖子的特定视图,即

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

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

    <% end %>

我觉得有一些简单的方法来完成这个我完全忘记了

【问题讨论】:

    标签: ruby-on-rails ruby arrays ruby-on-rails-3


    【解决方案1】:

    你可以做类似的事情

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

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

    【讨论】:

    • 这很有趣——我从没想过在不访问数据库时使用 .where 或 .find_by 路由。我最终选择了: post.views.find_by_user_id(current_user.id) 这就像一个魅力。非常感谢 Dogbert!
    • 它仍在访问数据库,rails 足够聪明,可以延迟执行查询,直到它需要...并且在这种情况下不会加载所有视图,只是那些你正在要求。看一下日志生成的SQL。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多