2

如何以不那么冗长的方式更新这些非常相似的文本字段?下面的文本字段被命名为给定 - 我没有为这个问题编辑它们。

  def update
    company = Company.find(current_user.client_id)
    company.text11 = params[:content][:text11][:value]
    company.text12 = params[:content][:text12][:value]
    company.text13 = params[:content][:text13][:value]
# etc
    company.save!
    render text: ""
  end

我试过使用sendto_sym但到目前为止没有运气......

4

2 回答 2

3
[:text11, :text12, :text13].each do |s|
    company.send("#{s}=".to_sym, params[:content][s][:value])
end

如果它们都是增量数字,那么:

11.upto(13).map{|n| "text#{n}".to_sym}.each do |s|
    company.send("#{s}=".to_sym, params[:content][s][:value])
end
于 2012-07-21T17:56:08.153 回答
0

我会考虑首先清理参数,然后再进行动态分配属性。围绕您的参数的包装类将允许您更轻松地对该代码进行单元测试。也许这有助于您入门。

require 'ostruct'

class CompanyParamsWrapper

  attr_accessor :text11, :text12, :text13

  def initialize(params)
    @content = params[:content]
    content_struct = OpenStruct.new(@content)
    self.text11 = content_struct.text11[:value]
    self.text12 = content_struct.text12[:value]
    self.text13 = content_struct.text13[:value]
  end
end

# Company model
wrapper = CompanyParamsWrapper.new(params)
company.text11 = wrapper.text11

# now easier to use Object#send or other dynamic looping
于 2012-07-21T17:59:19.163 回答