Rails has_many关联返回空数组

时间:2014-07-12 15:37:35

标签: ruby-on-rails

访问与用户关联的查询不会返回查询列表,而是返回空白数组。

例如:

   user = User.first 
     => [valid user]
   i = Inquiry.first 
     => [valid inquiry]
   i.user = user 
   user.inquiries
     => #<ActiveRecord::Associations::CollectionProxy []> 

我的三个模特:

user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :clients
  has_many :inquiries
end

client.rb

class Client < ActiveRecord::Base
  belongs_to :user

  validates :user_id, :name, presence: true
end

inquiry.rb

class Inquiry < ActiveRecord::Base
    belongs_to :user

    validates :user_id, :client_name, presence: true
end

客户端和查询模型在迁移文件中有t.references,index:true。

2 个答案:

答案 0 :(得分:2)

如果您使用:inverse_of方法帮助实现某些目标,则可以实现您想要的功能。所以定义你的关联如下:

class User < ActiveRecord::Base
  has_many :inquiries, inverse_of: :user
end

class Inquiry < ActiveRecord::Base
  belongs_to :user, inverse_of: :inquiries
end

您会注意到:inverse_of选项中使用的值等同于关联模型的关联名称。这种方式rails知道要检查逆模型的关系,这应该允许这个:

u = User.first
i = Inquiry.first
i.user = u
u.inquiries # => [i]

有关:inverse_of选项的更多信息,请在以下链接中搜索inverse_of

  1. http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to
  2. http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many

答案 1 :(得分:1)

由于您只是在控制台上进行试验,请尝试使用此类

user = User.first 
user.inquiries.create(whatever the params are for inquiry)

user.inquiries  # will return the inquiries, which for now is just the one in an array.

查看http://guides.rubyonrails.org/association_basics.html#has-many-association-reference了解详情