Почему это возвращает Nil в Ruby on Rails 3? - PullRequest
1 голос
/ 17 апреля 2011

Я выполнил эту команду:

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

Мысли?

Ответы [ 5 ]

2 голосов
/ 17 апреля 2011

Убедитесь, что plan_id находится в вашем списке attr_accessible вашей модели User или НЕ в вашем списке attr_protected. Это предотвратит назначение plan_id в этом операторе User.create.

1 голос
/ 17 апреля 2011

возможно, вам нужно добавить 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

Это связано с тем, что рельсы автоматически защищаются от массовых назначений.

1 голос
/ 17 апреля 2011

Вы пытались установить связь явно? Подобно тому, что сказал Саймон, но вроде:

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'.

1 голос
/ 17 апреля 2011

in 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, который устанавливается при создании.

1 голос
/ 17 апреля 2011

Попробуйте, скорее:

plan = Plan.find(4)
user1 = User.create(:email => 'test12@abc.com', :password => 'test12123', :username => 'test12', :first_name => 'Test', :last_name => 'User', :plan => plan)

Сбой из-за невозможности найти связанный объект "план".

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...