【问题标题】:has_many and belongs_to assosiations in Rails 4Rails 4 中的 has_many 和 belongs_to 关联
【发布时间】:2015-04-17 21:01:00
【问题描述】:

每个人 我在 Rails 中有一个与关系相关的问题。我有一个学生模型

class Student < ActiveRecord::Base
    ....
    has_many :histories, dependent: :destroy
end
                                  
                                 
还有我的历史模型

class History < ActiveRecord::Base
	belongs_to :student
	
end

我尝试使用此代码获取属于学生的所有历史记录

def history
@histories = @student.histories.paginate(:per_page =>25, :page => params[:page])
end
方法 history 属于 Students 控制器,通过 history_path(student) 调用。 但我得到一个错误:没有这样的列:histories.student_id。我想当我通过belongs_to 和has_many 在Rails 中建立关系时会自动创建许多必要的ID?

【问题讨论】:

  • 在软件中,除非在某处定义,否则不会自动执行任何操作。

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


【解决方案1】:

不,它们不是自动创建的。只需像这样创建迁移:

rails g migration add_student_id_to_histories student_id:integer

然后运行:

bundle exec rake db:migrate

这需要对所有关系进行。 Rails 不会自动创建它。您需要手动执行此操作。

【讨论】:

  • 谢谢,这对我有帮助。但是我有一个问题,如果我必须手动创建所有必要的 id 来设置关系,那么使用 has_many、belongs_to 关系有什么意义?对不起愚蠢的问题。在一些教程中,我看到他们创建了这种关系,但没有看到他们何时创建了这些 id,因此我开始认为 id 是自动生成的。 (例如 railsforzombies.org 2 讲座)。
  • 这些关联在很多地方都很有用。您可以在 google 上找到ORM 的优势。因为rails 中的Active Record 是ORM 的实现。我不是这方面的专家,但我注意到 ORM 简化了 SQL 查询,因为您不需要编写它。它提高了开发速度。代码更易理解。
【解决方案2】:

你必须尝试跑步:

rails g migration create_histories student:references; rake db:migrate

这将使用 student_id 创建历史记录表。 或者将 user:references 添加到您现有的历史记录表中

在我打字的时候先深度回答,避免我的回答。

【讨论】:

    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    相关资源
    最近更新 更多