Rails 3:控制器参数默认值
我正在使用远程 form_for 进行显示操作,以根据此表单传递的参数检索内容。
= 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 = ...
我的问题是,上述方法是否是我们可以为参数设置默认值的唯一方法,或者我们是否可以以更好的方式做到这一点。这可行,但我想知道这是否是正确的方法。
更新 根据下面的建议,我使用了以下内容并在 defaults.merge 行上收到错误:
defaults = {:content_type=>"type1"}
params = defaults.merge(params)
@content_type = params[:content_type]
I am using a remote form_for for my show action to retrieve content based on the params passed by this form.
= 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"
And I alter the content in controller as follows:
# 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 = ...
My question is, whether the above approach is the only we can set defaults for params or can we do it in a better manner. This works but I would like to know if this is the right approach.
UPDATE
Based on the suggestion below, I used the following and got an error on defaults.merge line:
defaults = {:content_type=>"type1"}
params = defaults.merge(params)
@content_type = params[:content_type]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
设置默认选项的一个好方法是将它们放在哈希中,并将传入的选项合并到其中。在下面的代码中,
defaults.merge(params)
将覆盖 params 哈希中的任何值来覆盖默认值。A good way of setting default options is to have them in a hash, and merge your incoming options onto it. In the code below,
defaults.merge(params)
will overwrite any values from the params hash over the default ones.如果有类型的静态列表,您可以将其设为下拉框,并且不包含空白选项,以便始终选择某些内容。但是,如果您被文本框困住了,您可以使用 before 过滤器来清理控制器操作:
If there is a static list of types you could make it a dropdown box and just don't include a blank option so that something is always selected. But if you're stuck with a textbox you could clean up the controller action by using a before filter:
我想在这个讨论中添加一种设置默认参数的工作方法:
这可以避免通过“params =”分配局部变量。
I wanted to add to this discussion a working way to set default params:
This avoids assigning a local variable via "params =".