【问题标题】:Rails 3: Associations with 3 combined modelsRails 3:与 3 个组合模型的关联
【发布时间】:2012-11-13 16:48:39
【问题描述】:

我无法通过关联访问模型。我有三个模型:

用户.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 

个人资料.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 

我认为上述关联有问题,知道吗?

【问题讨论】:

  • 我认为 Post has_one :profile 和 Profile has_many :posts 是错误的。但我不确定如何解决它。
  • 是的,我玩过:post has_many :profiles,但我得到了一个一般性的错误,它似乎是错误的。感谢您的建议。
  • 你为什么使用belongs_to :user, :polymorphic =&gt; true
  • 我正在使用 blogit gem,这实际上是 belongs_to :blogger, :polymorphic =&gt; true 但我更改了它以简化问题。
  • 只是一个猜测,但是从 User 中删除 has_many :posts 是否有任何作用,因为它已在 Profile.rb 中引用?

标签: ruby-on-rails ruby-on-rails-3 model associations


【解决方案1】:

尽量保持双方的关系:belongs_tohas_many/has_one。 所以在你的情况下你应该改变:

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

此外,您应该将profile_id 添加到您的posts 表中。

【讨论】:

  • 嗨!感谢您一直以来的帮助。我不想将 profile_id 添加到帖子中,因为我认为这不会满足我的需要。目前每个用户都有一个个人资料,每个用户可以写很多帖子。 Posts 有一个 user_id 字段,profiles 也有一个 user_id 字段。我需要链接这两者,最好使用关联。还有其他建议吗?
  • 是的,使用post.user.profile.forename。或者,将has_one :profile, throught: :user 更改为Post。在后一种情况下,按您的预期使用:@post.profile.forename.
  • 这太完美了!我添加了belongs_to :profile,使用了post.user.profile.forename。 (或者对于在这种情况下使用 BlogIt gem post.blogger.profile.forename 的极少数人)。谢谢马克!
【解决方案2】:

我认为你可以通过这样定义关联来做到这一点:

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

那么,你可以得到:post.profile.forename

希望这会有所帮助。

【讨论】:

  • 谢谢!这感觉更接近,但是belongs_to :user 是多态的,所以我得到Cannot have a has_many :through association 'Blogit::Post#profile' which goes through the polymorphic association 'Blogit::Post#blogger'.- 还有其他建议吗?
猜你喜欢
  • 1970-01-01
  • 2012-09-09
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多