ruby-on-rails - 如何向数组中的每个记录/对象添加属性/属性? rails

标签 ruby-on-rails arrays

我不确定这是否只是缺少 Rails 语言,或者我是否在 Stack Overflow 上搜索了所有错误的内容,但我不知道如何向数组中的每个记录添加属性。

这是我正在尝试执行的操作的示例:

@news_stories.each do |individual_news_story|
  @user_for_record = User.where(:id => individual_news_story[:user_id]).pluck('name', 'profile_image_url');
  individual_news_story.attributes(:author_name) = @user_for_record[0][0]
  individual_news_story.attributes(:author_avatar) = @user_for_record[0][1]
end

有什么想法吗?

最佳答案

如果 NewsStory 模型(或无论其名称是什么)与 User 具有 belongs_to 关系,那么您不必这样做任何这个。您可以直接访问关联的User的属性:

@news_stories.each do |news_story|
  news_story.user.name  # gives you the name of the associated user
  news_story.user.profile_image_url  # same for the avatar
end

为了避免 N+1 query ,您可以通过在 NewsStory 查询中使用 includes 一次性预加载每个新闻报道的关联用户记录:

NewsStory.includes(:user)... # rest of the query

如果您这样做,您将不需要 @user_for_record 查询 - Rails 将为您完成繁重的工作,并且您甚至可以看到性能改进,这要归功于没有发出单独的pluck 查询集合中的每个新闻报道。

如果您需要拥有这些额外的属性,无论如何:

您可以在 NewsStory 查询中选择它们作为额外属性:

NewsStory.
  includes(:user).
  joins(:user).
  select([
    NewsStory.arel_table[Arel.star],
    User.arel_table[:name].as("author_name"),
    User.arel_table[:profile_image_url].as("author_avatar"),
  ]).
  where(...) # rest of the query

关于ruby-on-rails - 如何向数组中的每个记录/对象添加属性/属性? rails ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45092049/

相关文章:

ruby-on-rails - 在 ActiveAdmin 的 'Custom Page' 中呈现自定义编辑部分

ruby-on-rails - 如何使用 Webpacker Assets 在 Rails Header 中内联 CSS

ruby-on-rails - 为什么 RubyMine 控制台无法启动?

arrays - slice 数组文字

ios - 如何将一个数组添加到另一个数组

ruby-on-rails - 多个用户的 Rails http 基本身份验证?

javascript - 如何将我的 current_user.id 传递给 AngularJs Controller

c - C 中结构体的指针数组

c - 无法使用命令行中的数组将字符串连接在一起并在 C 中一次读取一个字符

python - 将数组映射到其他数组,开头和结尾均为零