如何在 Ruby on Rails 应用程序中禁用所有 form_for 输入字段? [英] How to disable all form_for input fields in Ruby on Rails app?

查看:33
本文介绍了如何在 Ruby on Rails 应用程序中禁用所有 form_for 输入字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的 Rails 应用程序干一点,所以我想在我的 show 视图中呈现一个表单,但禁用所有输入字段.

//show.html.erb<%= form_for(@project) 做 |f|%><%= 渲染字段",:f =>f%><%结束%>

最好的方法是什么?

感谢您的帮助.

解决方案

Javascript

一种方法是使用 JS 来完成.在显示视图中包含具有特定类的 div :

//show.html.erb

<%= form_for(@project) 做 |f|%><%= 渲染字段",:f =>f%><%结束%>

然后在您的 JS 文件中:

$('.disable_input :input').prop('disabled', true);

导轨

如果您想在服务器端实际生成它,您可以将一个变量传递给您的部分,该变量将告诉部分是否必须在每个字段上添加禁用选项.不过工作量有点大!

使用变量,您可以执行以下操作:

<%= form_for(@project) do |f|%><%= 渲染字段",:f =>f, :disabled =>真%><%结束%>

在部分:

<% 禁用 ||= false#我们这样做是为了如果没有将 disabled 传递给部分它不会崩溃.# 我们默认为false%><% # 然后为所有字段添加 disabled: disabled %><%= f.text_field :some_attribute, disabled: disabled %>

表单生成器

实际上,避免在任何地方显式传递 disabled 的一种方法是创建一个 Custom form builder.有一些很好的资源在谈论它,比如这个:http://johnford.is/writing-a-custom-formbuilder-in-rails/

在这个例子中,它是为 onkeypress 完成的,应该不难适应你的情况!

I am trying to DRY up my Rails application a bit, so I would like to render a form in my show view but disable all input fields.

// show.html.erb

<%= form_for(@project) do |f| %>
  <%= render 'fields', :f => f %>
<% end %>

What would be the best way to do that?

Thanks for any help.

解决方案

Javascript

One way would be to do it using JS. Include a div with a specific class in the show view :

// show.html.erb

<div class='disable_input'>
  <%= form_for(@project) do |f| %>
    <%= render 'fields', :f => f %>
  <% end %>
</div>

Then in your JS file :

$('.disable_input :input').prop('disabled', true);

Rails

If you want to actually generate it server side, you can pass a variable to your partial that will tell the partial if it has to add the disabled option on each field. It's a bit more work though!

Using a variable, you could do something like this :

<%= form_for(@project) do |f| %>
  <%= render 'fields', :f => f, :disabled => true %>
<% end %>

In the partial :

<% disabled ||= false  
   #We do this so if disabled is not passed to the partial it doesn't crash. 
   # We default it to false 
%>

<% # Then for all your fields, add disabled: disabled %>
<%= f.text_field :some_attribute, disabled: disabled %>

Form builder

Edit : actually, one way to avoid explicitly passing disabled everywhere would be to create a Custom form builder. There's some good resources talking about it, like this one : http://johnford.is/writing-a-custom-formbuilder-in-rails/

In this example, it's done for onkeypress, shouldn't be hard to adapt for your case!

这篇关于如何在 Ruby on Rails 应用程序中禁用所有 form_for 输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆