ruby-on-rails - Ruby on Rails : How to join two tables

标签 ruby-on-rails join activerecord

我有一个索引页面,我想显示所有用户的个人资料及其相关照片。我正在为照片使用插件 Paperclip。在 Profiles Controller 中,我有实例变量 @profile 但它只向我显示了配置文件表中的表,而不是照片表。

@profile = Profile.find(:all, :include => :photos,
  :joins => "INNER JOIN photos ON photos.profile_id = profiles.id")

模型如下所示:
class Profile < ActiveRecord::Base
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :profile
end

我希望能够在 View 中显示的内容类似于:
  • 约翰的个人资料(例如姓名、年龄、性别)- 约翰的照片(例如,仅显示一张照片)
  • 此处玛丽的个人资料 - 此处显示玛丽的照片
  • 此处鲍勃的个人资料 - 此处显示鲍勃的照片
  • 最佳答案

    我已经编辑了我的答案以反射(reflect)您的额外评论。

    首先,您不需要 :joins范围; :include => :photos应该为您处理“幕后”加入。

    这是做你问的事情的一种方法。

    (在模型中)

    class Profile < ActiveRecord::Base
      has_many :photos
      has_one :primary_photo, :class_name => "Photo", :conditions => {:primary => true}
    end
    

    (在 Controller 中)
    @profiles = Profile.find(:all, :include => :primary_photo)
    

    (在 View 中)
    <% @profiles.each do |profile| %>
      Name: <%= profile.name %>
      Age: <%= profile.age %>
      Photo: <%= image_tag profile.primary_photo.url %>
    <% end %>
    

    关于ruby-on-rails - Ruby on Rails : How to join two tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/764538/

    相关文章:

    javascript - 未知关键字确保问题

    ruby-on-rails - Rails3/Sessions/Active_Record_Store/Signout --> 如何删除Sessions表中的cookie和记录?

    mysql - Active Record 精度小数值被截断

    php - PhpMyAdmin 中的请求与 Laravel 查询生成器一起工作,似乎不起作用

    mysql - 如何使 JOIN 查询使用索引?

    c++ - 想在 Qt 中存储配置文件,使用 SQLite 或其他东西?

    ruby-on-rails - 按日期排序时出现语法错误

    ruby-on-rails - 终端中持久存在 "bash:/home/XXX/.rvm/scripts/rvm: No such file or directory"

    ruby-on-rails - Android:如何在 Android 编程中编辑数据库中的特定记录(使用 Ruby on rails)

    mysql - 如何在需要连接的两个表中查询特定类型的电影名称?