Ruby-on-rails 使用 Rails Simple_form 预选复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4116415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:35:16  来源:igfitidea点击:

Preselect Check box with Rails Simple_form

ruby-on-railsruby-on-rails-3checkbox

提问by Drew

I'm using Simple_Formwith Rails 3 and it's great. I have a simple question. I can create a check box using f.inputif the type is boolean behind the scenes. However, I would like it to be preselected as true.

我在Rails 3 中使用Simple_Form,它很棒。我有一个简单的问题。我可以创建一个复选框,f.input如果类型在幕后是布尔值。但是,我希望它被预选为 true。

Is there a way to do this via the view?

有没有办法通过视图做到这一点?

采纳答案by PerfectlyNormal

the best way would be to set the default value in your model, something like

最好的方法是在模型中设置默认值,例如

create_table :my_table do |t|
  ...
  t.boolean :my_boolean, :default => true
  ...
end

which simple_formwill pick up on, and set the checkbox to be checked by default.

simple_form将启动,并将复选框设置为默认选中。

A simpler way is to do it as Dave says, and just force the value to 1, but if a validation fails, and you display the form again, it will still be checked, regardless of how it looked when the form was submitted.

一种更简单的方法是按照 Dave 所说的那样做,只需将值强制为 1,但是如果验证失败,并且您再次显示表单,它仍将被检查,无论表单提交时的外观如何。

回答by Gav

If you don't want to, or cannot update your migration to do 'PerfectlyNormal's answer, then you can add the following to the end of your f.input:

如果您不想或无法更新迁移以执行“PerfectlyNormal 的回答”,则可以将以下内容添加到 f.input 的末尾:

:input_html => { :checked => true }

So, it would become:

所以,它会变成:

= f.input :some_flag, :input_html => { :checked => true }

Hope that helps!

希望有帮助!

回答by anusha

It Worked for me which checks only one checkboxwith value of "None"

它对我有用,它只检查一个值为“无”的复选框

<%= f.input :notify, label: "Notification", as: :check_boxes, collection: ["None", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], :item_wrapper_class => 'inline', :checked => ["None", true] %>

回答by Michael Fehr

I just stumbled over this post and what worked for me is similar to the latest answer - but shorter. Just initialize the Object with the wished setting:

我只是偶然发现了这篇文章,对我有用的与最新的答案相似 - 但更短。只需使用所需的设置初始化对象:

def new
  Object.new(my_boolean: true)
end

回答by ndemoreau

In my opinion, the rail way to do this would be to set the value of the attribute in the controller:

在我看来,这样做的方法是在控制器中设置属性的值:

@some_object.some_flag = 1

@some_object.some_flag = 1

回答by Dave Rapin

This should work:

这应该有效:

= f.input :some_flag, :input_html => { :value => '1' }