Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Model Multiple Relationships in ActiveRecord?
    text
    copied!<p>I am trying to finish building a Rails "Home Inventory" app as an example to help me learn rails. Following gives a general overview of what I am trying to achieve:</p> <p>The main purpose of this application is to show a page with detailed information.</p> <p>So, <a href="http://localhost:3000/living-room-couch" rel="nofollow noreferrer">http://localhost:3000/living-room-couch</a> would display the information regarding the couch. </p> <p>Each Item, can belong one( or has one?) of three categories:</p> <ol> <li>Book</li> <li>Furniture</li> <li>Electronics.</li> </ol> <p><strong>Book</strong> has the following properties:<br> - isbn,<br> - pages,<br> - address,<br> - category </p> <p><strong>Furniture</strong> has following properties:<br> - color,<br> - price,<br> - address,<br> - category </p> <p><strong>Electronics</strong> has following properties:<br> - name,<br> - voltage,<br> - address,<br> - category.</p> <p>--</p> <p>Now on my <strong>View</strong> side, I have made 3 templates in rails, that contain elements suited to display an item belonging to one of the 3 categories. Template for <strong>Book</strong> shows isbn, and template for <strong>Electronics</strong> shows the voltage.</p> <p><strong>How do I model this in ActiveRecord?</strong> I will put it in English, maybe someone can help translate into Rails:</p> <p>An Item, belongs_to or has_one <em>category</em>. Category can be one of the three: <em>Book</em>, <em>Furniture</em>, or <em>Electronic</em>.</p> <p>I don't know how to do this. I know that each category like <strong>Book</strong> will be a model of its own, due to having different characteristics. </p> <p>Do I need to have <strong>Category</strong> has a model too, because it would only consist of <strong>Book</strong>, or <strong>Furniture</strong> or <strong>Electronics</strong>. If I was to take the route of making Category a model of its own, how would I make it relate to a model such as <strong>Book</strong>.</p> <hr> <p><strong>--or</strong></p> <p>Would I just go this route (or join model perhaps):</p> <pre><code>class BookModel &lt; ActiveRecord::Base has_many :categories End </code></pre> <p>And then, select to which category belongs, based on the Model name.</p> <p>I hope I put the question right, I am just so confused regarding this.</p> <p>Thank You for your time.</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