【问题标题】:ruby on rails get table row by two column conditionsruby on rails 按两列条件获取表格行
【发布时间】:2013-05-28 06:55:50
【问题描述】:

例如,我在数据库中有两个表,Users 和 Microposts。 Users 表存储所有用户,有两列,id 和 name; Microposts 表存储用户发布的帖子,并包含三列:id、post_content 和 user_id(当然,这两个表在创建每个条目时都有时间戳)。所以基本上我想要的是有一个视图页面,显示存储在用户中的信息(id 和名称)以及相应用户创建的最后一篇文章。 我正在考虑的一种方法是在用户视图页面(例如,位于 app/views/Users/index.html.erb 中)对其进行处理。因为我可能会像这样遍历用户表

<% @Users.each do |user| %>
    id = user.id
    <!-- Do such and such -->
<% end %>

在遍历用户表时,使用 user.id 获取用户发布的最新帖子。

第二种方法是基本上实现这样用户表有另一列存储最新的帖子信息,并在每次对数据库进行事务时更新。因此,在实现最新帖子时,可以将其作为属性访问。

但是,我真的不知道哪种方式更好,也不知道如何实施... 有什么建议吗? 提前致谢!


编辑: 对不起,有一个错字。就是“两表一库”

【问题讨论】:

  • 为什么你使用两个数据库,.. !!!!!
  • 如果你使用一个数据库和两个表,它的实现非常简单。然后你使用表关系。
  • 使用你的第一个实现。

标签: ruby-on-rails ruby database database-design


【解决方案1】:

与其他答案类似,但我想添加一个我认为通常被忽视的重要小部分。包括第一次调用数据库时的关联。

# not sure the scale of your project but I would paginate @users
# by using includes you prevent the N+1 issues
<% @users.includes(:microposts).each do |user| %>
    id = user.id
    user.microposts.last
<% end %>

有关这方面的一些文档:
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

【讨论】:

  • 欢迎您!还应注意,最好将 includes() 部分放在控制器中。
【解决方案2】:
    class User 
        has_many :microposts
    end

    class Micropost
        belong_to :user
    end

   # to get user's post 
   # for single user
    @user.microposts
   # for many users
    @users.each do |user|
        user.microposts.each  do  |post|
            post.post_content
        end
    end

【讨论】:

    【解决方案3】:

    您的用户有很多微博。所以在用户视图页面上执行以下操作,即 app/views/Users/index.html.erb

    <% @Users.each do |user| %>
        id = user.id
        last_post = user.microposts.last <!-- This will give you last post created by the user -->
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多