I have a searchbar on my landing page where I can search for books from users from different universities. It doesn't seem to accept the .joins when it gets redirected to the Book Index Page. Book belongs to user and user has many books.
I always get:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "user"
BooksController.rb
def index
if params[:book][:title].present? && params[:users][:university].present?
@books = Book.where({title: params[:book][:title]})
.joins(:user).where(user: {university: params[:users][:university]}).uniq
end
end
PagesController.rb
def home
@books = Book.new
end
And this is my search in simple_form:
<%= simple_form_for [@books], url: books_path, method: :get do |f| %>
<ul class="list-inline">
<li><%= f.input :title, placeholder: "Title", label: false %></li>
<%= simple_fields_for :users do |r| %>
<li><%= r.input :university, placeholder: "University", label: false %></li>
<% end %>
</ul>
<%= f.button :submit, 'search', class: "btn" %>
<% end %>
routes.rb
resources :books do
resources :users
end
Full error is:
LINE 1: ... "books"."user_id" WHERE "books"."title" = $1 AND "user"."un... ^ : SELECT DISTINCT "books".* FROM "books" INNER JOIN "users" ON "users"."id" = "books"."user_id" WHERE "books"."title" = $1 AND "user"."university" = $2>
The where
method expects to receive the exact table name (see full example here: How to query a model based on attribute of another model which belongs to the first model?):
@books = Book.where({title: params[:book][:title]})
@books = @books.joins(:user).where(users: {university: params[:users][:university]}).uniq
# ^ relation name ^ exact name of the table
If, for some reason, the name of the table storing the User
records was named utilisateurs
, then the where
usage would be:
@books = Book.joins(:user).where(utilisateurs: { name: 'Bob' })
Try using the plural form of the relationship with user to query by the university, like:
Book.where('title = ?', params[:book][:title])
.joins(:user)
.where(users: { university: params[:users][:university] }).uniq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With