在我的应用程序中,我有user
表和activities
表 - user
有activities
三种类型。我也有一个weeks
表 - 每activity
有一个集合数weeks
和user
拥有这些活动。所以weeks
属于users
和activities
,而activities
属于users
。下面是我的users
表:Ruby on Rails - 自动创建对象
class SorceryCore < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :surname
t.integer :previous_award
t.integer :chosen_award
t.string :email, :null => false
t.string :crypted_password
t.string :salt
t.timestamps
end
add_index :users, :email, unique: true
end
end
下面是我的活动表:
class CreateActivities < ActiveRecord::Migration
def change
create_table :activities do |t|
t.integer :activity_type
t.string :activity_name
t.string :approver_email
t.references :users, index: true, foreign_key: true
t.timestamps null: false
end
end
end
下面是我的周表:
class CreateWeeks < ActiveRecord::Migration
def change
create_table :weeks do |t|
t.integer :week_num
t.date :date_completed
t.time :time_completed
t.boolean :submitted
t.boolean :approved
t.references :activities, index: true, foreign_key: true
t.references :users, index: true, foreign_key: true
t.timestamps null: false
end
end
end
用户注册过程是一个多阶段报名。当用户注册时,他们也创建他们的3个活动。我想为每个活动自动创建一些周对象,并使用默认值。创建的这个周数应该等于来自用户注册过程的输入 - 来自用户表的被称为“所选奖励”的属性。 即我想周活动1的个数等于:
current_user.chosen_award
是否有办法来自动创建为每个追溯至当前的用户活动本周这些对象,使用默认值?
UPDATE: 周型号:
class Week < ActiveRecord::Base
belongs_to :activities
belongs_to :users
end
活动型号:
class Activity < ActiveRecord::Base
belongs_to :user
has_many :weeks, dependent: :destroy
$activity_type_var = 1;
end
用户模式:
class User < ActiveRecord::Base
has_many :activities, dependent: :destroy
has_many :weeks, dependent: :destroy
authenticates_with_sorcery!
validates :password, length: { minimum: 3 }
validates :password, confirmation: true
validates :email, uniqueness: true, email_format: { message: 'has invalid format' }
end
显示你的模型 –
为什么你需要'周'指的是'用户',因为'活动'是指'用户','周'是指'活动'已经? –
也许我不知道?我认为我需要创建这种关系,但你可能是对的,我不认为我需要在周表中包含user_id – Jarvey