Rails表现得很奇怪

时间:2013-07-21 20:46:04

标签: ruby-on-rails activerecord ruby-on-rails-3.2 associations

我有rails版本3.2.13和ruby版本1.9.3

我陷入了非常奇怪和有趣的境地。

在我的应用程序中有一个带有自定义验证器的模型“产品”。

product.rb

class Product < ActiveRecord::Base
  attr_accessible :description, :name, :price, :short_description, :user_id
  validates :name, :short_description, presence: true
  validates :price, :numericality => {:greater_than_or_equal_to => 0}
  validate :uniq_name

  belongs_to :user
  belongs_to :original, foreign_key: :copied_from_id, class_name: 'Product'
  has_many :clones, foreign_key: :copied_from_id, class_name: 'Product', dependent: :nullify

  def clone?
    self.original ? true : false
  end

 private

 #Custom validator

 def uniq_name
   return if clone?
   user_product = self.user.products.unlocked.where(:name => self.name).first
   errors[:name] << "has already been taken" if user_product && !user_product.id.eql?(self.id)
 end

end

在我尝试创建新产品时,产品控制器的创建操作

def create
  @product = current_user.products.new(params[:product])
  respond_to do |format|
    if @product.save
      format.html { redirect_to @product, notice: 'Product was successfully created.' }
      format.json { render json: @product, status: :created, location: @product }
    else
      @product.errors[:image] = "Invalid file extension" if @product.errors[:image_content_type].present?
      format.html { render action: "new" }
      format.json { render json: @product.errors, status: :unprocessable_entity }
    end
 end
end

当此行执行@product = current_user.products.new(params[:product])并且自定义验证程序的line # 2错误时,系统会调用自定义验证程序

undefined method `products' for nil:NilClass

我已在自定义验证程序中检查过产品对象,但user_id为零。 为什么user_id没有被自动分配?

我们将不胜感激您的帮助:)

2 个答案:

答案 0 :(得分:0)

所以...绕过你的问题。你为什么不只是验证名字的唯一性?

validates_uniqueness_of :name, :unless => :clone?

答案 1 :(得分:0)

尝试将.new更改为.build

@product = current_user.products.build(params[:product])

并确保您的用户模型中有关系

Class User < ActiveRecord::Base
  has_many :products