ruby-on-rails - 单个数据库条目 rails 3 的多个文本字段

标签 ruby-on-rails database ruby-on-rails-3 forms

在我正在构建的应用程序中,我需要将多个文本字段合并到一个数据库列中。

例如我的“业务”条目有一列“折扣”

我想阅读的文本字段是这样的:

<%= f.text_field :discount %> % Off <%= f.text_field :discount %>.  

我希望将这两个都作为字符串输入到数据库中:“10% Off Shoes”(或其他)。

有没有办法在 Rails 3 中做到这一点?

谢谢!

**编辑!

我尝试了 Pan Thomakos 的解决方案(使用虚拟属性),但现在出现以下错误:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.split
Extracted source (around line #3):

1: 
2: <%= f.label :cost %><br />
3: <%= f.text_field :percentage %> % Off <%= f.text_field :product %>.


app/models/business.rb:11:in `percentage'

我真的不知道该如何处理!不可否认,在模型中工作时我很弱,我可能会在 Controller 中处理它。

谢谢!

最佳答案

是的,最好的方法是使用虚拟属性。每个虚拟属性都会跟踪折扣的不同部分,折扣将是组合字段。以下是我将如何实现它:

class Business
  attr_writer :percentage, :product

  before_save :create_discount

  def percentage
    @percentage.nil? ? discount.to_s.split('% Off ').first : @percentage
  end

  def product
    @product.nil? ? discount.to_s.split('% Off ').last : @product
  end

  protected

  def create_discount
    discount = "#{@percentage}% Off #{@product}" unless @product.nil? || @percentage.nil?
  end
end

然后您可以将 View 修改为:

<%= f.text_field :percentage %> % Off <%= f.text_field :product %>.

关于ruby-on-rails - 单个数据库条目 rails 3 的多个文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5525680/

相关文章:

ruby-on-rails - Docker Rails 迁移

mysql - 使用 VB.Net 连接到在线 MySQL 数据库

database - 我如何将 href 与 id 号结合起来

javascript - Crypto Js 和 Rails 中的 AES 加密给出了不同的结果

ruby-on-rails-3 - 我应该将 api key 存储在 rails3 中的什么位置?

css - 有条件地使用 .less 样式表

ruby-on-rails - 用 Prawn 生成 PDF - 如何访问 Prawn.generate 中的变量?

ruby-on-rails - 如何给 ActiveAdmin 自己的应用程序布局? -- rails 新手

Mysql数据库数据维护

ruby - 向 Rails 3 中的延迟作业添加一些自定义方法?