【问题标题】:rails controller map unknownrails 控制器地图未知
【发布时间】:2016-12-19 20:21:26
【问题描述】:

authors_controller.rb,我有这个:

def show
    a = Author.find(params[:id])
    @author = a.map { |e| e.titlecase }
end

我收到一条错误消息,说 map 是 Author::0x007fec244142a0 的未定义方法。

我也试过这个:

def show
    @author = Author.find(params[:id])
    @author.each { |k, v| v.capitalize  }
end

如何将方法 titlecase 应用于 Author.find 的每个值?

【问题讨论】:

  • 您要大写哪些字段?
  • 每个字段.....

标签: ruby-on-rails methods controller


【解决方案1】:

find(params[:id]) 返回的不是数组,不是枚举器,也不是 Relation 类,而是模型的实例。您不能使用mapeach,所以只需将titlecase 应用于返回的对象。

def show
  @author = Author.find(params[:id])
  @author.name = @author.name.titlecase # if you have column 'name'
end

但最好将标题名称移动到模型的方法中,或者在需要的地方使用@author.name.titlecase

您可以使用where 并使用map 运算符:

def show
  @author = Author.where(id: params[:id])

【讨论】:

  • 那么这意味着我不能将任何方法迭代地应用于类实例中包含的方法?
  • 可以遍历所有属性@author.attributes.each{|k,v| @author[k] = v.capitalize if v.respond_to?(:capitalize)}
【解决方案2】:

它很丑,但它有效。我确信有更好的方法来做这些事情。

@author.attributes.map do |k,v| 
  v = @author.__send__(k).capitalize if @author.__send__(k).respond_to?(:capitalize)
end
@author.save

但我必须说,我不建议这样做。最好将模型中的每个字段都大写

【讨论】:

  • 是也不是,有时更明确会更好更安全。干燥代码是一个很好的一般规则,但不应太过分。但这只是我的意见,我相信其他人会不同意。
【解决方案3】:

据我了解。您想将所有记录字段大写Author.find(params[:id]) 对吗?

首先,Author.find(params[:id]) 将返回一条记录,而不是数组。这意味着您不能为此使用eachmap

将记录的所有字段大写。你可以试试:

def show
  author = Author.find(params[:id])
  @author = author.attributes.values.map{|field| field.to_s.capitalize}
end

它将返回一个包含所有字段值的数组。

更新 1

为了更好

def show
  author = Author.find(params[:id])
  @author_info = author.attributes.values.map{|field| field.is_a?(String) ? field.capitalize : field}
end

【讨论】:

  • 我不建议这样做,因为它会将所有内容都大写,甚至将 created_at 等内容更改为字符串然后大写。
  • created_at 可能类似于2016-11-04 02:46:23 utc。我觉得没关系,在他的问题上,他说How can I apply the method titlecase to each value of Author.find ?
  • 还有一点,@author 现在是一个数组,而不是Author 的一个实例,所以你不能像一个活动记录对象那样工作,保存和更新。
  • 为什么我们需要更新show 操作?正如我所说,可能是thiebo 想要在一个数组中列出作者的所有信息。我还更新以使代码更好。请看一下。
  • 最好是,但你也可以使用field.is_a?(String)。我仍然会检查它是否响应大写,但就像我说的那样,这些只是我的意见。
猜你喜欢
  • 1970-01-01
  • 2016-01-12
  • 2022-08-18
  • 1970-01-01
  • 2023-04-04
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多