0

関連付けを介してモデルにアクセスできません。私は3つのモデルを持っています:

ユーザー.rb

class User < ActiveRecord::Base
 devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

 has_one :profile
 has_many :posts
 attr_accessible :email, :password, :password_confirmation, :remember_me
end 

Profile.rb

class Profile < ActiveRecord::Base
 belongs_to :user, :dependent => :destroy
 has_many :posts
 attr_accessible :currentlatitude, :currentlongitude, :forename, :surname, :profpicture, :notes                      
end

Post.rb

class Post < ActiveRecord::Base
 ...
 attr_accessible :title, :body, :tag_list, :blogger_id, :coverphoto, :locations_attributes
 belongs_to :user, :polymorphic => true
 has_and_belongs_to_many :locations
 has_one :profile
end

投稿のタイトルの横にある投稿のインデックス ビューに Profile.forename を表示したいのですが、試してみると、

<%= post.profile.forename %> 

次のエラーが表示されます。

SQLite3::SQLException: no such column: profiles.post_id: SELECT  "profiles".* FROM "profiles"  WHERE "profiles"."post_id" = 56 LIMIT 1 

上記の関連付けに何か問題があると思いますが、何か考えはありますか?

4

2 に答える 2

1

両側からの関係を保つようにしてください: belongs_to<=> has_many/has_one. したがって、あなたの場合、変更する必要があります:

class Post < ActiveRecord::Base
 ...
 belongs_to :profile
 ...
end

また、それが機能するためには、テーブルに追加profile_idする必要がありpostsます。

于 2012-11-13T17:12:24.510 に答える
0

次のように関連付けを定義することでできると思います。

class Post < ActiveRecord::Base
  ...
  has_one :profile, :through => :user
end

次に、次を取得できます。post.profile.forename

これが役立つことを願っています。

于 2012-11-13T17:42:55.187 に答える