我跑了这个命令:
user1 = User.create(:email => 'test12@abc.com', :password => 'test12123', :username => 'test12', :first_name => 'Test', :last_name => 'User', :plan_id => '4')
并收到此错误:
NoMethodError: undefined method `trial_duration' for nil:NilClass
这是我的用户模型:
# == Schema Information
# Schema version: 20110412170916
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# encrypted_password :string(128)
# password_salt :string(255)
# reset_password_token :string(255)
# remember_token :string(255)
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# username :string(255)
# first_name :string(255)
# last_name :string(255)
# created_at :datetime
# updated_at :datetime
# invitation_token :string(60)
# invitation_sent_at :datetime
# plan_id :integer
# current_state :string(255)
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# space_used :integer default(0), not null
# failed_attempts :integer default(0)
# unlock_token :string(255)
# locked_at :datetime
# trial_end_date :date
# active_subscription :boolean
#
belongs_to :plan
before_create :set_trial_end
def set_trial_end
plan = self.plan
end_of_trial = self.created_at + plan.trial_duration.days
self.trial_end_date = end_of_trial
end
这是我的计划模型:
# == Schema Information
# Schema version: 20110412101615
#
# Table name: plans
#
# id :integer not null, primary key
# name :string(255)
# storage :float
# num_of_projects :integer
# num_of_clients :integer
# cached_slug :string(255)
# created_at :datetime
# updated_at :datetime
# amount :integer
# trial_duration :integer
# trial_duration_unit :string(255)
# currency :string(255)
# billing_cycle :integer
# billing_cycle_unit :string(255)
#
class Plan < ActiveRecord::Base
has_many :users
has_many :subscriptions
has_friendly_id :name, :use_slug => true
end
想法?
答案 0 :(得分:2)
确保:plan_id位于用户模型的attr_accessible列表中,或者不在attr_protected列表中。这将阻止在该User.create语句中分配plan_id。
答案 1 :(得分:1)
试试这个:
plan = Plan.find(4)
user1 = User.create(:email => 'test12@abc.com', :password => 'test12123', :username => 'test12', :first_name => 'Test', :last_name => 'User', :plan => plan)
由于没有找到相关的“计划”对象而失败。
答案 2 :(得分:1)
您是否尝试过明确设置关联?与西蒙所说的相似,但是像:
plan = Plan.find(4)
user = [code to create the user, but without the "plan" or "plan_id" attribute]
user.plan = plan
user.save
或者,在您的代码中,尝试使用:plan_id => 4
代替'4'
。
答案 3 :(得分:1)
在before_create :set_trial_end
中尚未提取该计划。
我认为您需要在def set_trial_end
def set_trial_end
plan = Plan.find(plan_id)
end_of_trial = self.created_at + plan.trial_duration.days
self.trial_end_date = end_of_trial
end
您可能需要一个名为plan_id的虚拟属性,该属性在创建时设置。
答案 4 :(得分:1)
也许你必须将trial_duration添加到你的attr_accessible。
试试这个:
class Plan < ActiveRecord::Base
has_many :users
has_many :subscriptions
has_friendly_id :name, :use_slug => true
attr_accessible :trial_duration
end
这是因为导轨自动防止大规模分配。