干我Rails代码:

时间:2010-11-09 20:14:48

标签: ruby-on-rails dry

我有几个,其中唯一不同的是它的text_field或password_field等等。 我想将此作为参数传递给渲染,例如:as => :password_field例如。 而且我不想做一个案例比较,传递的值是:就像字段的值一样。这可能吗?


.text{:class => form.object.errors[field].any? ? "error" : nil}
  = form.label field
  -if defined? value
    = form.text_field field, :value => value
  -else
    = form.password_field field 
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field           

.text{:class => form.object.errors[field].any? ? "error" : nil}
  = form.label field
  -if defined? value
    = form.text_area field, :value => value
  -else
    = form.text_area field 
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field => field 

答案如下,有一些修正:


-# expects form, field_name, field_type, value and hint variables to be passed
.text{:class => form.object.errors[field_name].any? ? "error" : nil}
  = form.label field_name
  - if defined?(value)
    = form.send(field_type, field_name, :value => value)
  - else
    /= form.send(:field_type, field_name)   
    = form.send(field_type, field_name)   
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field => field_name        

使用方法: = render 'shared/form_field', :form => f, :field_name => :email, :field_type => :text_field

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你就是在这之后:

render :partial => 'user/login_errors', :locals => { :field => :first_name, :value => @user.first_name, :form => form }

使用locals哈希传递任意数量的变量。在您的情况下,代码段中的变量为formfieldvalue。散列中的键确定变量将在partial中引用的内容,散列中的值确定变量值。

答案 1 :(得分:1)

创建一个名为shared/form_field.html.haml

的部分
- # expects form, field_name, field_type, value and hint variables to be passed
.text{:class => form.object.errors[field_name].any? ? "error" : nil}
  = form.label field_name
  - if defined?(value)
    = form.send(:field_type, field_name, :value => value)
  - else
    = form.send(:field_type, field_name)
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field => field_name 

您可以调用partial作为

- form_for :user do |form|
 = render 'shared/form_field', :locals => {:form => form, 
                        :field_name => :login, :field_type => :text_field}