3

Say I have the following models:

class Parent < ActiveRecord::Base
  has_one :child
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

I'd like to retrive the parent through the child, but doing the following fails: I find the model in the following way through a controller

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

(Not sure if this is relevant, but since I'm using shallow routing, the parent_id is not available in the URL)

In my view, I'd like to retrieve the child's parent like this:

@child.parent

How would I go about doing this?

Thanks!


Update: my example (when I decided to start a new app and create it) actually ran perfectly. In my actual app, I forgot to include belongs_to :parent in the child's model. How silly of me. Thanks for taking the time to comment and answer, guys. Next time I'll look more carefully before posting a question here.

4

1 に答える 1

9

それはまさにあなたがそれを行う方法です。

@childそれが機能していないという事実は、親を持つことを妨げている根本的な問題があることを示唆しています.

まず、 のテーブルにChild外部キーがあることを確認します。外部キー列 (この場合parent_idは ) は、関連付けを持つモデル上に常に存在する必要がありますbelongs_to

次に、フェッチしている子に実際に親があることを確認します。これは、外部キー ( parent_id) が nil であってはならないことを意味します。数値の場合は、 のテーブルにParentのforeign_key と同じ値を持つレコードがあることを確認してくださいChild

Rails コンソール (rails consoleアプリケーション ディレクトリから) を使用して、関連付けを再確認することもできます。やっChild.first.parentてみて、何が起こっているか見てください。もちろん、Parent.first.childまたはなどのバリエーションをChild.find(123).parent使用することもできますが、 は使用できませんparams

于 2010-12-26T02:16:25.880 に答える