How to find child parent through has_one association in Rails3?

Let's say I have the following models:

class Parent < ActiveRecord::Base
  has_one :child
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

I would like to return the parent through the child, but do the following: I find the model as follows through the controller

@child = Child.find(params[:child_id])

(Not sure if this is relevant, but since I use shallow routing, parent_id is not available in the url)

In my opinion, I would like to get the child parent element as follows:

@child.parent

How should I do it?

Thank!


: ( ) . belongs_to :parent . . , , , . , .

+3
1

.

, , , @child .

, , Child . ( parent_id) belongs_to.

-, , , , . , (parent_id) . , , Parent , foreign_key Child.

Rails (rails console ) . Child.first.parent , . , , Parent.first.child Child.find(123).parent, params.

+9
source

Source: https://habr.com/ru/post/1782135/


All Articles