【发布时间】:2021-04-13 11:25:07
【问题描述】:
这似乎是一件非常简单的事情,但尽管查看了 rails 文档,但它并没有像我预期的那样工作。我可能在某处做出了不正确的假设。也许我正试图让 activerecord 用于它不打算用于的东西?
我正在尝试加入我的 Books 表和 Checkout_logs 表,并且只返回匹配 user_id 且返回日期为 null (nil) 的记录
我正在尝试在 sql 中执行类似此示例的操作(除了列出所有书籍信息,而不仅仅是标题并从参数中获取 user_id)
select b.title,c.due_date from
(select * from books) b
JOIN
(select * from checkout_logs) c
ON b.id = c.book_id
where c.user_id = 1 and returned_date is null
这是我的尝试
books_controller.rb
def my_books
@books = Book.joins(:checkout_logs).where(user_id: params[:user_id], returned_date: nil)
end
并查看
my_books.html.erb
<table>
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Subgenre</th>
<th>Pages</th>
<th>Publisher</th>
<th>due_date</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody>
<% @books.each do |book| %>
<tr>
<td><%= link_to book.title, book %></td>
<td><%= book.author %></td>
<td><%= book.genre %></td>
<td><%= book.subgenre %></td>
<td><%= book.pages %></td>
<td><%= book.publisher %></td>
<td><%= book.due_date %></td>
<td><%= link_to 'Return', books_return_path %></td>
</tr>
<% end %>
</tbody>
</table>
book.rb
class Book < ApplicationRecord
has_many :checkout_logs, dependent: :destroy
end
checkout_log.rb
class CheckoutLog < ApplicationRecord
belongs_to :user
belongs_to :book
end
加载books.user_id 不存在或books.due_date 不存在的视图时会出错。我知道书籍没有这些东西,但我认为通过将其与 checkout_log 结合,我就可以通过这种方式访问它们?
我更愿意学习如何在 activerecord 中执行此操作,因为我认为这是最佳实践。我愿意使用另一种方法。我有另一个使用 AREL 执行类似操作的页面,但如果我可以学习如何更好地使用 activerecord,我更愿意清理它。
【问题讨论】:
-
where(checkout_logs: {user_id: params[:user_id], returned_date: nil})
标签: sql ruby-on-rails postgresql rails-activerecord