Note that there are some explanatory texts on larger screens.

plurals
  1. POSequel - Query Many to Many Associations
    text
    copied!<p>I am having issues constructing the proper models, associations, and query for the following scenario and then returning results as JSON using Sequel with Ruby.</p> <p>The database structure___</p> <p>You can create a list of books. Each library contains books. Defined by the following:</p> <pre><code>db.create_table(:books) do primary_key :id String :name String :author DateTime :created end db.create_table(:libraries) do primary_key :id String :name String :city String :state DateTime :created end db.create_table(:libraries_books) do Integer :library_id Integer :book_id primary_key [:library_id, :book_id] end class Library &lt; Sequel::Model(:libraries) many_to_many :libraries_books, :left_key=&gt;:library_id, :right_key=&gt;:book_id, :join_table=&gt;:libraries_books one_to_many :libraries_books, :key=&gt;:library_id end class LibraryBook &lt; Sequel::Model(:libraries_books) many_to_one :libraries many_to_one :books end </code></pre> <p>I am trying to determine the correct way to access all the book names for a given library. I initially tried to follow the Sequel Associations guide but was not able to figure out how I could use LibraryBook with associations to get all the books for a library and join on the Book model to get the proper columns.</p> <p>After getting stuck with some of the methods described, I attempted to create my own query as such:</p> <pre><code>LibraryBook.select(:books.*) .join_table(:inner, :libraries, :id =&gt; :library_id) .join_table(:inner, :books, :id =&gt; :book_id) .where(:library_id =&gt; 1) </code></pre> <p>Which seems to get me partially there. However, when I use the serialization extension, I get an error when the results are being converted:</p> <pre><code>undefined method `book_id' for #&lt;LibraryGame:0x007fa9e904b470&gt; </code></pre> <p>Any insight into that can be provided would be very helpful!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload