在我的應用程序中,我有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