加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – Rails 3:控制器参数默认值

发布时间:2020-12-17 04:19:02 所属栏目:百科 来源:网络整理
导读:我正在使用远程form_for进行show动作,以根据此表单传递的参数检索内容. = form_tag modelname_path(@modelname),:id="select_content_form",:remote = true,:method = 'get' do = text_field_tag :content_type,params[:content_type],:id="select_content_t
我正在使用远程form_for进行show动作,以根据此表单传递的参数检索内容.
= form_tag  modelname_path(@modelname),:id=>"select_content_form",:remote => true,:method => 'get' do               
  = text_field_tag :content_type,params[:content_type],:id=>"select_content_type"
  = submit_tag "submit",:name => nil,:id=>"select_content_submit"

我改变控制器中的内容如下:

# Default params to "type1" for initial load
if params[:content_type]
  @content_type = params[:content_type];
else
  @content_type = "type1"
end

case @content_type

when "type1"
  # get the content
  @model_content = ...

when "type1"
  # get the content
  @model_content = ...

我的问题是,上述方法是否是我们唯一可以为params设置默认值的方法,还是我们能够以更好的方式进行.这有效,但我想知道这是否是正确的方法.

UPDATE
基于下面的建议,我使用以下内容并在defaults.merge行上出错:

defaults = {:content_type=>"type1"}
params = defaults.merge(params)
@content_type = params[:content_type]

解决方法

设置默认选项的一种好方法是将它们放在哈希中,并将传入的选项合并到它上面.在下面的代码中,defaults.merge(params)将覆盖默认值的params散列中的任何值.
def controller_method
    defaults = {:content=>"Default Content",:content_type=>"type1"}
    params = defaults.merge(params)
    # now any blank params have default values

    @content_type = params[:content_type]
    case @content_type
        when "type1"
            @model_content = "Type One Content"
        when "type2"
            #etc etc etc
    end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读