Rails-text_field中的默认值,但仅适用于new_record吗? [英] Rails - default value in text_field but only for new_record?

查看:91
本文介绍了Rails-text_field中的默认值,但仅适用于new_record吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在内容模型上,有一个名为 slug 的属性。创建新记录时,我想使用一个助手来填充该字段,但是在现有记录上,我想使用数据库中的值。

On a Content model have an attribute named slug. When creating a new record, I want to use a helper to populate this field, but on an existing record I want to use the value from the database.

目前,我有:

<% if @content.new_record? %>
  <%= f.text_field :slug, :value => "#{generate_slug(6)}" %>
<% else %>
  <%= f.text_field :slug %>
<% end %>

但这似乎有些冗长。这是最好的方法,还是没有其他方法? (Rails newb只是尝试在我不确定的问题上找到 Rails方式)

But that seems a bit verbose. Is this the best way, or is there no other way? (Rails newb just trying to find the "Rails way" on issues I'm unsure of)

编辑

我应注意,该助手当前位于/app/helpers/application_helper.rb 中,已成为其中的私人操作目录控制器。大卫的答案很棒。

I should note that the helper is currently in /app/helpers/application_helper.rb Moved to be a private action in the Contents controller. David's answer worked great.

推荐答案

在您的控制器中

@content.slug ||= generate_slug(6)

这将分配 slug 属性的值(如果不存在)

This will assign a value to the slug attribute if none is present

然后,在您看来,您可以简单地使用

Then, in your view you can simply use

<%= f.text_field :slug %>

这篇关于Rails-text_field中的默认值,但仅适用于new_record吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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