【问题标题】:Detecting whether to show or to process a form based on GET or POST检测是否显示或处理基于 GET 或 POST 的表单
【发布时间】:2012-04-27 21:07:13
【问题描述】:

我有一个User 模型和一个Account 控制器。当用户访问/account url 时,它应该显示一个表单,其中包含一个包含用户名的文本字段和一个提交表单的按钮。

我的路线中有match '/account' => 'account#index'

在我的控制器中,我定义了这个方法:

def index
  @user = User.find(session[:user_id])
end

(检查用户身份验证发生在before_filter

现在表单可以正确显示,甚至可以正确填充。但是,我需要知道如何判断表单是否已提交。什么是铁轨方式?我是否有单独的路由来监视对/accountPOST 请求?还是我在index 方法中检测请求类型?我在什么时候决定表单是否已提交?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 routing rails-routing


    【解决方案1】:

    您可以检测表单是否已在索引控制器内部提交。我相信 params 哈希将密钥 :method 设置为用于请求的方法。

    另一种方法是重做您的路线。而不是match '/account' => 'account#index' 你可以这样做:

    get '/account' => 'account#index'
    post '/account' => 'account#post_action'
    

    然后在你的控制器内部你可以这样做:

    def index
      @user = User.find session[user_id]
    end
    
    def post_action
      @user = User.find session[user_id]
      if @user.update_attributes params[:user]
        flash[:notice] = 'Update Successful'
        render :action => index
      else
        flash[:notice] = 'Update Unsuccessful'
        render :action => index
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2012-02-12
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 2011-03-16
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多