ruby-on-rails – 将has_many设置为inverse_of:通过rails 4.1

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 将has_many设置为inverse_of:通过rails 4.1前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
该文档意味着inverse_of将适用于除多态关联之外的所有内容.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Setting+Inverses

但是,似乎inverse_of仍然不适用于has_many:through

例如我在以下示例中为inverse_of尝试的每个组合都不起作用

class Event  < ActiveRecord::Base
  has_many :attendances
  has_many :users,through: :attendance
class User < ActiveRecord::Base
  has_many :attendances 
  has_many :events,through: :attendances
class Attendance < ActiveRecord::Base
  belongs_to :event
  belongs_to :user

任何这方面的想法应该起作用?如果是这样,在这个例子中如何设置inverse_of?

UPDATE

例如我试过的(也试过has_many:通过)

class Event  < ActiveRecord::Base
  has_many :attendances,:inverse_of => :event
  has_many :users,through: :attendance
end
class User < ActiveRecord::Base
  has_many :attendances,:inverse_of => :user
  has_many :events,through: :attendances
end
class Attendance < ActiveRecord::Base
  belongs_to :event,:inverse_of => :attendances
  belongs_to :user,:inverse_of => :attendances
end

也试过

class Event  < ActiveRecord::Base
  has_many :attendances  
  has_many :users,through: :attendance,:inverse_of => :events
end
class User < ActiveRecord::Base
  has_many :attendances 
  has_many :events,through: :attendances,:inverse_of => :users
end
class Attendance < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

解决方法

我在轨道4.1.6中也有同样的问题(这是我如何绊倒这个问题).

它花了一些试验和错误(和服务器重新启动),但以下工作对我来说:

class User < ActiveRecord::Base
  has_many :company_users
  has_many :companies,through: :company_users
end

class Company < ActiveRecord::Base
  has_many :company_users
  has_many :users,through: :company_users
end

class CompanyUser < ActiveRecord::Base
  belongs_to :company,inverse_of: :company_users
  belongs_to :user,inverse_of: :company_users
end

为了清楚起见:

例:

user = User.last
company = user.companies.build( ... )
company.save
# ...
# sql (0.9ms)  INSERT INTO "public"."company_users" ("company_id","created_at","updated_at","user_id") VALUES ($1,$2,$3,$4) RETURNING "id"  [["company_id",4],["created_at","2014-10-03 03:40:58.836975"],["updated_at",["user_id",1]]
(1.6ms)  COMMIT
CompanyUser.last
<CompanyUser:0x00000020339710> {
        :id => 4,:company_id => 4,:user_id => 1,:created_at => Thu,02 Oct 2014 20:40:58 PDT -07:00,:updated_at => Thu,02 Oct 2014 20:40:58 PDT -07:00
}

所以基本上我只是在连接模型中设置了inverse_of

原文链接:https://www.f2er.com/ruby/267115.html

猜你在找的Ruby相关文章