2

如果我想根據客戶中的用戶是否被singned_in實現一些驗證,我們是否可以在我們的Rails模型文件中編寫條件語句。 rb文件。Ruby on Rails模型文件中的條件語句

if user_signed_in? // if signed_in is true 
    //my validation code here 

那麼一些特殊的驗證和

else !user_signed_in? // if signed_in is false 
    //my validation code here 
+0

嘿,我覺得你可以試試'if'和'elsif' –

回答

4

current_useruser_signed_in?等不在型號。

Rails 3 devise, current_user is not accessible in a Model ?

總之,你的用戶爲中心的條件,應在控制器,該模型是拉&操縱數據 ...

enter image description here

我發佈這個圖像一直在;它顯示了標準框架的外觀。 Rails 是一個MVC框架的 ...向您展示了模型和其他元素如何協同工作以使其正常工作。

正如您所看到的,控制器的作用類似於將所有這些粘合在一起的「集線器」。爲了使您的應用程序結構正確,您最好將您的中級邏輯放入您的控制器,將數據級邏輯放入您的模型中,並將表面邏輯放入您的視圖中。

EG:

#Model 
class Products 
    belongs_to :user 
end 

#controller 
def index 
    @products = user_signed_in? ? current_user.products : Product.all 
end 

#view 
<% @products.each do |product| %> 
    <%= product.name if product.name %> 
<% end %> 

您需要的答案是指定所需的驗證邏輯,讓您在控制器應用所需的數據/模型


如果你想使用用戶驗證模型中,您必須使用控制器級別的條件並將結果傳遞給模型:

#app/controllers/users_controller.rb 
class UsersController < ApplicationController 
    def create 
     @user = User.new user_params 
     @user.online = user_signed_in? 
    end 

    private 

    def user_params 
     params.require(:user).permit(:x, :y, :z) 
    end 
end 

#app/models/user.rb 
class User < ActiveRecord::Base 
    validates :online, presence: true 
end 
+1

而且它有時是有用的創建「命令」或「服務」類從兩個控制器_and_車型保持這種邏輯的路程。 https://blog.engineyard.com/2014/keeping-your-rails-controllers-dry-with-services – mahemoff

+0

@RichPeck:我的問題是驗證客戶輸入的電子郵件ID,如果user_signed_in?是真的,那麼電子郵件必須驗證所有可能的驗證。如果沒有signed_in,那麼不需要檢查唯一性,如何解決這個問題,你能幫我嗎? –

+0

爲什麼你不只是驗證電子郵件表格;我沒有看到他們被登錄有什麼重要的事情呢? –

0

這樣的事情?

validates :my_attribute, presence: :true, if: :user_signed_in? validates :my_attribute, presence: :false, unless: :user_signed_in?