Note that there are some explanatory texts on larger screens.

plurals
  1. PORails - How to associate models in one direction only
    text
    copied!<p>Ahoy guys,</p> <p>I'm new to Rails, and I feel like I'm definitely missing something crucial here, because it seems like this should be an easily solvable problem.</p> <p>I've set up a <code>Page</code> model and a <code>Coord</code> model (with help from the getting started tutorial), and <code>Coord</code> successfully <code>belongs_to</code> <code>Page</code>. I'm trying to apply similar logic to make another model, <code>Comment</code>, belong to <code>Coord</code>, and only belong to <code>Page</code> via <code>Coord</code>.</p> <p>Do I use <code>:through</code> for an association that (I think) only needs to link in one direction? As in Page &lt; Coord &lt; Comment? At the moment I have:</p> <pre><code>class Page &lt; ActiveRecord::Base attr_accessible :description, :name has_many :coords has_many :comments, :through =&gt; :coords end </code></pre> <p>Coord model:</p> <pre><code>class Coord &lt; ActiveRecord::Base belongs_to :page has_many :comments attr_accessible :coordinates, :x, :y validates :x, :presence =&gt; true validates :y, :presence =&gt; true end </code></pre> <p>Then the Comment model:</p> <pre><code>class Comment &lt; ActiveRecord::Base belongs_to :coord belongs_to :page attr_accessible :body end </code></pre> <p>I still keep getting errors about <code>comments</code> being an undefined method, or an association not being defined. Apologies if this is a common question, I don't personally know anyone who knows Rails, and the documentation only has examples too far removed from mine (to my knowledge). Thanks</p> <p><strong>Edit: added DB schema</strong></p> <pre><code>ActiveRecord::Schema.define(:version =&gt; 20120712170243) do create_table "comments", :force =&gt; true do |t| t.text "body" t.integer "coord_id" t.integer "page_id" t.datetime "created_at", :null =&gt; false t.datetime "updated_at", :null =&gt; false end add_index "comments", ["coord_id"], :name =&gt; "index_comments_on_coord_id" add_index "comments", ["page_id"], :name =&gt; "index_comments_on_page_id" create_table "coords", :force =&gt; true do |t| t.string "coordinates" t.integer "x" t.integer "y" t.integer "page_id" t.datetime "created_at", :null =&gt; false t.datetime "updated_at", :null =&gt; false end add_index "coords", ["page_id"], :name =&gt; "index_coords_on_page_id" create_table "pages", :force =&gt; true do |t| t.string "name" t.string "description" t.datetime "created_at", :null =&gt; false t.datetime "updated_at", :null =&gt; false end end </code></pre>
 

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