【问题标题】:Rails params explainRails 参数说明
【发布时间】:2015-11-24 11:43:35
【问题描述】:

我关注this tutorial。 我无法理解rails 中的params[]。请不要向我提供rails 指南的链接。我已经读过,仍然不清楚。我的疑惑是

  1. 我可以给出什么论据
  2. 什么是 params[:folder] & params[:id]
  3. 如果它是我们传递的列名,那么我的表中没有文件夹列。列在我的文件夹表中:id、name、created_at、updated_at
  4. 我使用的是 rails 4.2.4,所以我读过的一些地方 attr_accessible 被使用了,但现在它已经过时了。那么用什么来代替 attr_accessible 呢?

    class FoldersController < ApplicationController 
      before_filter :authenticate_user! 
    
      def index 
        @folders = current_user.folders 
      end
    
      def show 
        @folder = current_user.folders.find(params[:id]) 
      end
    
      def new
        @folder = current_user.folders.new
      end
    
      def create 
        @folder = current_user.folders.new(params[:folder]) 
      end
    end
    

这是我的第二个控制器。我怀疑这里的folder_id是什么

    class HomeController < ApplicationController 

      def browse 
        #get the folders owned/created by the current_user 
        @current_folder = current_user.folders.find_by_id(params[:folder_id])   
      end
    end

【问题讨论】:

  • params 包含请求参数。如果您导航到/folders/1234?foo=bar,那么params[:id] 将是1234params[:foo] 将等于"bar"

标签: ruby-on-rails ruby


【解决方案1】:

嗯,params 是一系列 key-value 对,来自带有页面请求的浏览器。对于HTTP GET 请求,params 编码在URL 中。

对于这样的请求:

http://www.example.com/?foo=1&bar=cat

那么params[:foo] 将是"1"params[:bar] 将是"cat"

HTTP/HTML 中,params 实际上只是一系列key-value 对,其中keyvalue 是字符串,但Rails 具有使params 成为的特殊语法Hash 内部带有哈希值。

对于这样的请求:

http://www.example.com/folders/55/?folder[name]=bubble&folder[size]=1324

那么,
params[:folder] 将是 Hash
params[:folder][:name] 将是 "bubble"
params[:folder][:size] 将是 "1324"。此外,
params[:id] 将是 "55"


Rails 4 现在使用strong parameters

保护属性现在在控制器中完成。像这个例子:

class ArticleController < ApplicationController
  def create
    Article.create(article_params)
  end

private

  def article_params
    params.require(:article).permit(:name, :category)
  end
end

【讨论】:

    【解决方案2】:

    params 对象只是一个散列,其中包含随请求发送到服务器的参数。例如,如果您使用GET 请求访问端点/folders/1,这意味着您正在运行FoldersController#show 操作,您将拥有一个包含:id 键的散列(依次声明在路线中,因为您可能正在使用resources :folders 方法)。您可以使用params[:id] 访问它,从而返回1。如果您在查询字符串中传递任何其他参数,它们也将可用:访问/folders/1?show_details=true 将产生一个包含:show_details 键的params 对象,映射到值true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2016-11-25
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多