1
私はActiveRecordではなくActiveModelを使用しています。そして、私のモデルは次のとおりです。 RubyでHTTPレスポンスをどのように処理するのが最適でしょうか?
class User
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
validates :name, :presence => true, :length => { :maximum => 50 }
validates :email, :presence => true,
:format =>
{
:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
}
validates :password, :presence => true, :confirmation => true,
:length =>
{
:within => 6..40
}
attr_accessor :name, :email, :password, :password_confirmation
def initialize(attributes = {})
@name = attributes[:name]
@email = attributes[:email]
@password = attributes[:password]
@password_confirmation = attributes[:password_confirmation]
end
def persisted?
false
end
def save
# createUser calls RESTful HTTP server and gets back JSON in http response's body
response = createUser(self.name, self.email, self.password)
end
end
そして、私は上記の方法を保存することにより、返されたこの応答を処理しようとすると、以下の私のusers_controller.rbで
が、それはパスワードとpassword_confirmationのための私のモデルの検証を台無しに。def create
@user = User.new(params[:user])
response = @user.save
parsed_response_body = ActiveSupport::JSON.decode(response.body)
# response body I have is {"ok":"ok message"} OR {"error":"error message"}
message = parsed_response_body["error"]
if @user.valid? && message.nil?
flash[:success] = message
redirect_to signup_path
else
@user.password = ""
@user.password_confirmation = ""
flash[:error] = message
render :action => 'new'
end
end
以下は、検証を破ることのないコントローラコードです。この場合、@ user.saveはtrueを返しています。
def create
@user = User.new(params[:user])
if @user.valid? && @user.save
flash[:success] = "Done"
redirect_to signup_path
else
@user.password = ""
@user.password_confirmation = ""
flash[:error] = "Not Done"
render :action => 'new'
end
end
誰かがこれで私を助けることができる場合、私は感謝するだろう。..
特に質問は何ですか? –
@mark私の質問は、コントローラの応答を処理するためのコードを追加すると、ユーザーのパスワードとpassword_confirmationの検証が中断されるのはなぜですか?レスポンスの処理に何か問題がありますか? –