0
votes

I am trying to make an app with Rails 4 and Simple Form.

I have three models, being: Project, Scope and Background.

Project has one scope. Scope has one background. Scope belongs to project. Background belongs to scope. Project accepts nested attributes for Scope. Scope accepts nested attributes for background.

Project.rb: has_one :scope accepts_nested_attributes_for :scope

Scope.rb:

belongs_to :project accepts_nested_attributes_for :background

Background.rb

belongs_to :scope

The scope params are permitted in the project controller. Also, the background attributes are permitted inside the project controller (as scope attributes).

The background params are also permitted in the background controller.

The permitted params in each controller include the id for itself and for the model that it belongs to.

So in the:

background controller, the permitted params include :scope_id and :background_id) scope controller, the permitted params include :project_id

I am trying to find a background by its project_id.

When I type:

 Background.where(:project_id => 95)

I get an error. I don't have a project_id foreign key in my background table (because background belongs to scope).

How do I search in the rails console for a nested attribute?

2

2 Answers

0
votes

One way I believe you could accomplish this is first finding the scope by project_id and then from there get the background of that scope (since a scope has one background):

scope = Scope.where(:project_id => 95).take
background = scope.background

You could potentially chain them together:

Scope.where(:project_id => 95).take.background

(Note, haven't tested the code so please let me know if this works)

Hope this helps!

0
votes

One way could be

Background.includes(:scope).where('scopes.project_id = ?', 95).references(:scope).first