Rails - 使用设备以访客身份撰写评论。设计主张?
我希望能够以访客或注册用户的身份使用设备撰写评论。
我的评论模型包含 :title、:content、:user_id、:guest_email、:guest_website< /strong> 和 :write_as_guest 作为布尔值。
我想仅在没有用户登录时验证 :guest_email 是否存在。但我认为我并没有朝着好的方向发展。
我正在使用 AJAX/jQuery 管理表单,我想要一个访客表单,其中 :content 和 :guest_email 是必需字段。另一方面,我希望用户表单中只需要 :content 。
以下是我尝试的方法。
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
但是我不想验证创建,因为那是访客...
所以如果有人能够向我提出一种以访客或用户身份编写的方法,那就是真的很感激。
谢谢
I want to be able to write a comment as a guest or as a registered user with devise.
My comment model contains :title, :content, :user_id, :guest_email, :guest_website and :write_as_guest as a boolean.
I wanted to validate the presence of :guest_email only when no user is signed_in. But I think I'm not going in the good direction.
I'm managing the form with AJAX/jQuery and I wanted to have a guest form where :content and :guest_email are necessary fields. In another hand, I want to have the user form where only the :content is necessary.
Here is how I tried to go for it.
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
It seems that user_signed_in? method needs before_filter :authenticate_user! then I have the following in my comments_controller
before_filter :authenticate_user!, :only => :create
But however I don't want to authenticate to create because that's a guest...
So if somebody would be able to propose me a way to write as a guest or as a user, that would be really appreciated.
Thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像这样进行自定义验证
You can do a custom validation like this