在ActiveRecord模型中添加关联的好处?

时间:2013-08-22 19:35:04

标签: ruby-on-rails activerecord associations rake datamapper

我是第一次创建活跃的记录关联,并希望了解添加它们后会发生什么。我正在使用rails 3.2.14

我有3个表用户,应用程序和工作

1]在应用程序表中,我添加了User_Id和Job_id作为外键列,因为应用程序属于User和Job。

2]我还添加了必要的关联。

3]添加外键列和关联后,运行rake db:migrate足够还是我必须做其他任何事情来完成关系建模?

某些情境

现在当我在点击作业链接后创建一个新应用程序时,我希望job_id和user_id将由Application:create方法中的框架自动填充

Application.new(params[:application])

但是,似乎外框没有填充foreign_key列,我必须在create方法中手动提取相关的job_id和user_id,并将其填充到应用程序中。

不添加关联的一个好处是,如果我后来发现某些关系是has_and_belong_to_many而不是has_many我可以在表中处理它,因为在那时没有关联被“冻结”。

我有以下问题:

1]在模型中定义关联有什么好处。我本来可以添加外键列并处理它们而不在模型中关联它们。

2]通过在模型中添加关联,我应该期待什么其他事情(最终会让我的生活更轻松)?

以下是模型:

Models:
    class User < ActiveRecord::Base
      rolify
      # Include default devise modules. Others available are:
      # :token_authenticatable, :confirmable,
      # :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable

      # Setup accessible (or protected) attributes for your model
      attr_accessible :role_ids, :as => :admin
      attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :user_id
      validates_presence_of :email

    end


    class Job < ActiveRecord::Base
      attr_accessible :company, :desc, :location, :application_id, :applicant_id

      belongs_to :recruiters, :class_name => "User"
      has_many :applications
      has_many :applicants,:class_name => "User", through: :applications
    end

    class Application < ActiveRecord::Base
      attr_accessible :applicant_email, :applicant_name, :recruiter_id, :applicant_id, :user_id


      belongs_to :jobs
      belongs_to :applicants, :class_name => "User"
    end

注意 您可以在评论部分提供视频,博客的链接,以简单的方式解释这些内容。我没有找到有助于理解所有步骤的官方文档,http://guides.rubyonrails.org/association_basics.html并且没有相关的rails-cast我可以找到

1 个答案:

答案 0 :(得分:0)

1)因为它们使代码中的常见操作更简单,更容易。它本质上是Active Record模式。为什么要编写代码来自己处理这些内容,比如查询等已经内置的内容。它可以显着减少代码并使查询更容易阅读。 2)这太宽泛了,所以我不会。