如何将has_many和belongs_to更改为has_many和has_many?

时间:2014-07-29 13:16:31

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

有用户模型和日程安排模型 首先,我想要有一个属于一个用户的许多时间表 现在我想要有许多用户/很多用户的日程安排
这是我的代码片段:

用户模型:

# encoding: UTF-8
require 'bcrypt'
class User < ActiveRecord::Base
  [...]
  has_many :schedules
  [...]
end

时间表模型:

# encoding: UTF-8
class Schedule < ActiveRecord::Base
  belongs_to :user
  [...]
end


数据库属性是:
用户模型:
时间表没有属性。
时间表模型:
user_id为整数

如何正确更改?

<小时/> 修改
产生输出:

class CreateUsersSchedulesJoinTable < ActiveRecord::Migration
  def change
    create_join_table :users, :schedules do |t|
      # t.index [:user_id, :schedule_id]
      # t.index [:schedule_id, :user_id]
    end
  end
end

class RemoveUserIdFromSchedule2 < ActiveRecord::Migration
  def change
    remove_column :schedules, :user_id, :integer
  end
end

SQL:

Started GET "/" for 127.0.0.1 at 2014-07-29 16:05:25 +0200
Processing by WelcomeController#index as HTML
User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 12 LIMIT 1
Schedule Load (1.0ms)  SELECT "schedules".* FROM "schedules" INNER JOIN "schedules_users" ON "schedules"."id" = "schedules_users"."schedule_id" WHERE "schedules_users"."user_id" = $1 ORDER BY "schedules"."date_time" ASC  [["user_id", 12]]
Rendered welcome/index.html.erb within layouts/application (0.0ms)
Completed 200 OK in 48ms (Views: 44.0ms | ActiveRecord: 2.0ms)

迁移工作正常。现在有一个带有id的新表,但我也必须更改控制器,因为我的订单方法没有工作atm。任何人都可以帮助我吗?

class WelcomeController < ApplicationController

  def index
    if(current_user)
      @user_schedules = current_user.schedules
      @user_schedules_date = @user_schedules.order(:date_time).group_by { |sched| sched.date_time.beginning_of_day }
    end
  end

end

1 个答案:

答案 0 :(得分:1)

你应该使用连接表,你可能想要命名新表:'users_schedules',这个新表应该包含两列:user_id和schedule_id(使用迁移):

class CreateUsersSchedulesJoinTable < ActiveRecord::Migration
  def change
    create_table :users_schedules, id: false do |t|
      t.integer :user_id
      t.integer :schedule_id
    end
  end
end

另一个删除上表中的旧列:

class RemoveUserIdColumns < ActiveRecord::Migration
    def change
        remove_column :schedule, :user_id
    end
end

然后将您的模型更新为

class User < ActiveRecord::Base
    has_and_belongs_to_many :schedules
    .....
end

class Schedule < ActiveRecord::Base
    has_and_belongs_to_many :users
    .....
end

这应该有效!