Mel Mel - 1 month ago 9
Ruby Question

Rails - how to associate nested models

I have an organisation model and I have also made a series of nested models under the folder name "stance". One of those models is called overview.

The associations are:

Organisation.rb

has_one :overview


Stance::Overview

belongs_to :organisation


My controllers for stance resources are nested under a folder called stance.

My routes are:

namespace :stance do
resources :overviews
end


In my stance view partial, I am trying to render the attributes from the overview table.

I have tried:

<p><%= @overview.internal_explanation %></p>
<p><%= @stance.overview.internal_explanation %></p>
<p><%= @stance::overview.internal_explanation %></p>


I want to display this partial in my organisation show, but I can't figure out how to access the overview table. Do I need to add a reference to 'stance' in the associations?

I can see that in the console I need to write:

o = Stance::Overview.create(internal_explanation: "test")


but I can't see how to use that in the code itself.

Answer

If you don't use the standard naming convention, then you need to give Rails some hints:

has_one :overview, class_name: Stance::Overview

belongs_to :organisation, inverse_of: :overview

Best place to learn this is to look at the source code comments on has_many and belongs_to. I'd recommend using an editor that has a "go to source"/"go to declaration" functionality that allows you to CTRL-click a method name and jump into the gem code so you can see the comments. I used this via Rubymine when I was learning Ruby and it was an enormous help.