开发者

Rails - Write comment as a guest with devise. Design proposition?

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.wri开发者_如何学Pythonte_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


You can do a custom validation like this

class Comment < ActiveRecord::Base
  validate :guest_commentator

    def guest_commentator
      user = User.find(user_id)
      self.errors.add(:user_id => "some error message here ") unless user.nil? 
    end
  end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜