1
我希望能夠以設計者的身份或作爲註冊用戶撰寫評論。Rails - 以設計方式撰寫評論。設計主張?
我的評論模型包含:標題,:內容,:user_id說明,:guest_email,:guest_website和:write_as_guest作爲一個布爾值。
我想驗證是否存在:guest_email只有當沒有用戶是signed_in。但我認爲我不會朝着好的方向前進。
我使用AJAX/jQuery管理表單,我想要一個訪客表單,其中:content和:guest_email是必需的字段。另一方面,我想讓用戶只需要:內容是必要的。
這是我試圖去做的。
class Comment < ActiveRecord::Base
before_validation :set_write_as_guest
belongs_to :user
validates_presence_of :content
validates_presence_of :guest_email, :if => :write_as_guest?
private
def write_as_guest?
self.write_as_guest
end
def set_write_as_guest
if user_signed_in?
self.write_as_guest = false
else
self.write_as_guest = true
end
end
end
看來user_signed_in?方法需要before_filter:authenticate_user!然後,我已經在我的comments_controller以下
before_filter :authenticate_user!, :only => :create
但是,無論我不想驗證創建,因爲這是一個客人......
所以,如果有人將能夠提出我的方式來寫作爲客人或作爲用戶,這將是非常感激。
THX
自定義驗證不用戶協會(或沒有)暗示客人?也許這樣做:def write_as_guest? return user_id == 0 end – leonm
Here you go:[如何創建訪客用戶](https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user) – sled
Thx我用你的鏈接臨時創建和登錄訪客用戶。我將用戶字段:角色設置爲「guest」,將註釋字段write_as_user設置爲「true」,以幫助我在驗證評論是否由訪客編寫時進行驗證。 – Bachet