【问题标题】:How to query with has_may/belongs_to associations in controller?如何在控制器中查询 has_may/belongs_to 关联?
【发布时间】:2015-08-10 04:31:30
【问题描述】:

我真的很困惑 has_many 和 belongs_to 在控制器中是如何工作的,更具体地说是如何查询数据。

我有一个用户模式和任务模型,一个用户可以有许多任务并且任务属于一个特定的用户。

这是我的模特:

class Task < ActiveRecord::Base
  belongs_to :user

  validates :title, 
            presence: true, 
            length: {minimum: 5, maximum: 50}

  validates :description, 
             presence: true, 
             length: {minimum: 1, maximum: 140}
end

class User < ActiveRecord::Base
   has_many :tasks, dependent: :destroy

   has_secure_password

   validates :email, 
             presence: true, 
             uniqueness: true    
 end

例如,在我的任务控制器中,我将如何实现相同的操作:

    def index
       # Get all tasks from database
       @tasks = Task.all
       # how would you achieve the same thing, but only show tasks that belong to a specific user? something like this:
       @tasks.users.find(:all)?
   end

我一直在做研究,但我似乎无法掌握这一点。无论如何,任何解释都会有很大帮助。谢谢大家。

http://guides.rubyonrails.org/active_record_querying.html

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many

【问题讨论】:

    标签: ruby ruby-on-rails-4 rails-activerecord models


    【解决方案1】:

    首先使用 find 或 find_by_id 找到用户记录。

    user = User.find_by_id(id)

    然后在用户对象上调用任务,这将列出该特定用户的所有任务。

    list_of_tasks = user.tasks

    【讨论】:

      【解决方案2】:

      有关查询 has_many 关联的正确方法,请参阅 Rails 的有关预加载关联的文档(特别是 includes 方法):

      http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

      我不确定您想从数据库表中提取什么样的信息,但这里有几个示例说明您可以如何查询所有任务及其相关用户。

      @tasks_and_users = Task.all.includes(:user)
      
      @tasks_and_users.each do |task|
        puts "The user with email '#{task.user.email}' has this task: #{task.title}"
      end
      

      或者,如果您想要一份所有用户(无论他们是否有任何任务)及其相关任务的列表,可以使用以下替代方法:

      @users_and_tasks = User.all.includes(:tasks)
      
      @users_and_tasks.each do |user|
        puts "The user with with email '#{user.email}' has the following tasks:"
        user.tasks.each do |task|
          puts "\t Task: #{task.title}"
        end
      end
      

      【讨论】:

      • 使用 has_many 时特定控制器的操作约定是什么?他们会变成什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多