0

我有軌版本3.2.13和紅寶石版本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未被自動分配?

您的幫助將不勝感激:)

+1

嘗試使用'.build'而非' .new' –

+0

你確定它是因爲驗證而發生的,而不是因爲current_user是零嗎?在你的驗證碼中,一切都很好。 – gvalmon

+0

@gvalmon如果它是零用戶錯誤味精會不同 - 我想寫,但是,線,沒有指定 –

回答

0

所以...繞過你的問題。你爲什麼不只是驗證名稱的獨特性?

validates_uniqueness_of :name, :unless => :clone?

0

嘗試改變。新來.build

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

,並確保您在用戶模式有關係

Class User < ActiveRecord::Base 
    has_many :products