在我正在构建的应用程序中,我需要将多个文本字段合并到一个数据库列中。
例如我的“业务”条目有一列“折扣”
我想阅读的文本字段是这样的:
<%= 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/