文章与多个作者模型关系

时间:2017-03-17 07:43:29

标签: ruby-on-rails ruby-on-rails-4

我正在创建一个维基百科类型的博客,其中一篇文章有​​多位作者。例如:第1条是由john创建的,后来由steve,bob,jane等编辑。然后,如何创建模型,如果我查询Article1.authors,它为我提供了Article1的所有作者,即john,steve,bob,简和他们编辑的时间。这是一个学习的个人项目。我不知道如何使用模型关系。

1 个答案:

答案 0 :(得分:0)

我认为你应该用这一行创建一篇文章模型:

has_many :authors

这一行的作者模型:

belongs_to :article

多亏了这一点,你应该访问文章模型中的所有作者,所以在你的文章控制器中,如果你写:

# all articles
def index
  @articles = Article.all
end

def show
  @article = Article.find(params[:id])
  # here you have access to all the authors
  @authors = @article.authors
end

我希望这有帮助!

相关问题