Search code examples
ruby-on-railsruby-on-rails-3validationparametersmodels

Rails model not getting the params correctly


i'm having a kinda weird & annoying bug with Rails. I have a HAML form, a model, and a method for handling it:

View

%form{ :action => "/new", :method => "post", :style=>"margin-top: 6px"}
    %input{:type=>"hidden", :name=>"authenticity_token", :value=>form_authenticity_token.to_s}
    %input{:type => "text", :name => "blogName", :placeholder=>"Blog name"}
    %input{:type => "text", :name => "blogSubdomain", :placeholder=>"Blog URL"}

    %input{:type => "text", :name => "username", :placeholder=>"username"}

    %input{:type => "text", :name => "email", :placeholder=>"email"}

    %input{:type => "password", :name => "password", :placeholder=>"password"}

    %br/
    %input{:type => "submit", :value => "Send", :class => "btn btn-primary"}

- unless session[:error].nil?
    %div{:class=>"alert alert-error", :style=>"font-size:13px; font-weight:normal;"}
        %strong Please correct the following errors
        %br
        - session[:error].each do |value|
            - unless value.nil?
                %li= "#{value}"
                - session[:error]=nil

Model:

class User
    include MongoMapper::Document

    key :screen_name, String,       :required => true, :unique => true
    key :blog_name, String,         :required => true, :unique => true
    key :blog_subdomain, String,    :required => true, :unique => true
    key :email, String,             :required => true, :unique => true, :format => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i
    key :password, String,          :required => true
    key :admin, Boolean

    timestamps!

    validate :finalValidate

    before_save :stripSpaces, :hashPassword

    def stripSpaces
        self.blog_subdomain = self.blog_subdomain.gsub(/[\ _]/, "-")
    end
    def finalValidate
        if blog_subdomain.length > 10
            errors.add(:blog_subdomain, "Your chosen subdomain is too long, the maximum is 9 characters")
        end
        case blog_subdomain
            when "www"
            when "api"
            errors.add(:blog_subdomain," - Sorry but that subdomain is reserved!")
        end
    end
    def hashPassword
        self.password = Digest::SHA512.hexdigest(self.password)
    end
end

And the method to do it

def new_post
        if session[:r]
            redirect_to root_path, :subdomain => nil
        else
            user = User.new({
                :screen_name=>params[:username],
                :blog_name => params[:blogName],
                :blog_subdomain => params[:blogSubdomain],
                :email => params[:email],
                :password => params[:password],
                :admin => false
            })
            if user.save
                session[:screen_name] = user.screen_name
                session[:blog_subdomain] = user.blog_subdomain
                session[:blog_name] = user.blog_name
                session[:twitter_user] = "nothin"
                session[:r] = true
                flash[:success] = "Blog created!"
                redirect_to root_path, :subdomain => user.blog_subdomain
            else
                errors = Array.new()
                for i in 0..user.errors.full_messages.count
                    errors.push(user.errors.full_messages[i])
                end
                session[:error] = errors
                flash[:error] = "Error creating blog"
                redirect_to '/new'
            end
        end

    end

The method fails on if user.save, going straight to the else statement. I'm getting errors when passing the email and password. MongoMapper returns:

  • Email can't be blank
  • Email has already been taken
  • Email is invalid
  • Password can't be blank

If I remove the validations then the values are just nil. I double checked all, but I couldn't get what's wrong. On the log I see how the params are being sent:

Started POST "/new" for 127.0.0.1 at 2012-03-10 20:46:56 +0100
  Processing by ActionsController#new_post as HTML
  Parameters: {"authenticity_token"=>"T7J8DDaWWd25LBP6dRgbvpAs4bkC/zLk3GiQ5rVLmiw=", "blogName"=>"wut", "blogSubdomain"=>"WUT", "username"=>"someuser", "email"=>"some@validmail.net", "password"=>"[FILTERED]"}
Redirected to http://myapp.dev/new
Completed 302 Found in 745ms

What I'm doing wrong?

EDIT: Put a logger on the model, and bot mail and password classes are NilClass


Solution

  • The problem was attr_accessible. I didn't added the email and password fields to it, and it was returning nil because of that