0

I have two models. The first is events and the second cities. in the events table i have an column which called city_id. I want the city name on each event show view.

In the events controller:

@city = City.where(:id => @event.city_id)

And in the view:

<%= @city.name %>

A city has many events and a event belongs to a city.

The output in my view is just the word city.

Hm, Where is the mistake?

4

1 に答える 1

1

コードを次から変更します。

@city = City.where(:id => @event.city_id)

に:

@city = @event.city

必要以上に長いだけでなく、元のコードは実際にはActiveRecord::Relationオブジェクト (遅延ロードされたクエリ) を都市のコレクションに対して返します。呼び出し@city.nameは、そのリレーションのクラス名を取得していました。これは「City」です。.firstクエリをトリガーして最初のレコードを取得するように追加すると、正しく機能します。

@city = City.where(:id => @event.city_id).first

しかし、上で述べたように、これは必要以上に多くのコードです ;)。もちろん、これはbelongs_to :cityEvent クラスにステートメントを設定することを前提としています。

于 2013-05-13T18:22:45.153 に答える