Rails:你能检查一个简单的字符串比较方法的语法吗?

时间:2010-12-14 20:22:09

标签: ruby-on-rails syntax

它将存储在数据库中的实际密码(@ submission.password)与用户从视图中输入的密码(params [:password])进行比较。 如果它们相同,则删除提交。

这是字符串比较方法。

def compare_password
    if @submission.password == params[:password] # This line is wrong.
        @submission = Submission.find(params[:id])
        @submission.destroy
        redirect_to(@submission, :notice => 'Listing deleted successfully')
    else
        redirect_to(@submission, :alert => 'Password is incorrect.')
    end
end

这是观点。

<%form_tag "/submissions/compare_password" do%>
<%=text_field_tag :password, params[:password]%>
<%=submit_tag "Delete"%>
<%end%>

我得到的执行错误就是这个。

undefined method `password' for nil:NilClass

修改

最初我的routes.rb看起来像这样

resources :submissions do
    collection do 

        post :compare_password
    end
end 

现在我改为

resources :submissions do
    member do 

        post :compare_password
    end
end 

1 个答案:

答案 0 :(得分:1)

@submission为零 - 您需要在检查密码值之前找到它 -

def compare_password
    @submission = Submission.find(params[:id]) # it is nil till you get it here
    if @submission && (@submission.password == params[:password])
        @submission.destroy
        redirect_to(@submission, :notice => 'Listing deleted successfully')
    else
        redirect_to(@submission, :alert => 'Password is incorrect.')
    end
end