Модель Rails не получает параметры правильно - PullRequest
0 голосов
/ 11 марта 2012

У меня какая-то странная и раздражающая ошибка с Rails. У меня есть форма HAML, модель и метод для ее обработки:

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

Модель:

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

И способ сделать это

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

Метод не выполняется на if user.save, переходя прямо к оператору else. Я получаю ошибки при прохождении email и password. MongoMapper возвращает:

  • Электронная почта не может быть пустой
  • Письмо уже занято
  • Email недействителен
  • Пароль не может быть пустым

Если я уберу проверки, то значения будут nil. Я дважды проверил все, но я не мог понять, что не так. В журнале я вижу, как отправляются параметры:

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

Что я делаю не так?

РЕДАКТИРОВАТЬ: Поставьте регистратор на модель, и бот mail и password классы NilClass

Ответы [ 2 ]

0 голосов
/ 11 марта 2012

Проблема была attr_accessible.Я не добавил к нему поля адреса электронной почты и пароля, и он возвращал ноль из-за этого

0 голосов
/ 11 марта 2012

Не должно быть там скорее

user = User.new(
                :screen_name=>params[:username],
                :blog_name => params[:blogName],
                :blog_subdomain => params[:blogSubdomain],
                :email => params[:email],
                :password => params[:password],
                :admin => false
            )

?

...