Rails:引用该对象所属的模型

Sha*_*moe 6 model ruby-on-rails include relationship

这可能是一个愚蠢的问题,但我似乎无法找到一个好的答案.我想知道引用一个对象所属模型的最佳方法.

例如:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :users
end
Run Code Online (Sandbox Code Playgroud)

所以,为了获得用户的帖子,我可以使用user.posts,但是为了获得帖子的用户,我不能这样做:post.user

如果我向Post模型添加"用户"方法,它可以工作,但它似乎不是最好的方法.

class Post < ActiveRecord::Base
  belongs_to :users

  def user
    User.find(self.user_id)
  end
end
Run Code Online (Sandbox Code Playgroud)

如果你看这篇博客文章http://www.fortytwo.gr/blog/18/9-Essential-Rails-Tips作为例子,你可以看到作者使用post.user.username,这不起作用开箱即用以及:include => [:user],即使使用Post模型中的"user"方法也不起作用.

我知道这很简陋,所以感谢你的耐心等待.我只是想知道实现这种关系的最佳方法.

我的主要目标是使用嵌套包含来编写"查找",它会像这样引用给用户:

post = Post.find(:all,:include => [:user])

当我尝试这个时,我得到"ActiveRecord :: ConfigurationError:未找到名为'user'的关联;也许你拼错了它?"

非常感谢.

Cho*_*ett 8

我对Rails有点新意,但这应该会自动生效......

啊 - 你已经在Post中命名了父类belongs_to :users; 但由于它只属于一个用户,因此Rails期待belongs_to :user(当然belongs_to :users, :class_name => "User").

那是:

class Post < ActiveRecord::Base
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

应该做的工作.