【发布时间】: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