我不确定这是否只是缺少 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/