用相同记录中的其他内容替换红宝石切片的内容

时间:2019-06-24 14:33:18

标签: ruby-on-rails

需要以下调用才能为第三方库生成JavaScript。

@items = Item.where('id IN (?) AND  type_id = ?', @all_valid_items, 1).all
@records = @items.map{|a| a.slice('brand', 'producer', 'title')}

以下是用于生成所需字符串的模型方法,该字符串应仅代替title属性数据而生成。

def title_text
  "#{title}<br />#{main_text}"    
end

但是将该逻辑扩展为slice方法

@records = @items.map{|a| a.slice('brand', 'producer').merge({'title' => a.title_text.join})}

使用

时返回undefined method 'title_text' for #<Item:
@records = @items.map{|a| a.slice('brand', 'producer').merge({'title' => a.values_at('title','main_text').join})}

a.values_at返回undefined method 'values_at' for #<Item:

生成修改后的字符串的正确语法是什么?

1 个答案:

答案 0 :(得分:1)

请尝试使用以下代码合并数据:

@items.map{ |a| a.slice(:brand, :producer, :title).merge(title: a.title_text.html_safe) }

.html_safe等效于raw(some_string),您可以在模型或控制器中使用它。