我有以下型号:
class Audit < ActiveRecord::Base
has_one :country, :through => :another_model
has_and_belongs_to_many :questions
end
class Question < ActiveRecord::Base
has_and_belongs_to_many :audits
has_many :details # one detail for each country [england, wales, scotland etc]
has_one :detail, :conditions?
# i want it to have one detail dynamically depending on the audit
end
class Detail < ActiveRecord::Base
belongs_to :country
belongs_to :question
end
问题在于question
模型。比方说,我有审计A,问题1,2和3,审计A位于英格兰国家。查看审核A时,我想显示3个问题;没问题。 @audit.questions.each do |q|
等
现在让我们解释一下问题的细节。假设我有细节X,Y和Z.细节X,Y和Z都与问题1相关。但是,细节X位于英格兰国家,威尔士细节Y和苏格兰细节Z.目前,我已将所有详细信息从数据库中删除,然后在视图/模型中获取当前审计的国家/地区,然后根据该数据获取详细信息。
有没有办法说出以下内容:
class Question < ActiveRecord::Base
has_and_belongs_to_many :audits
has_one :detail, :conditions -> {country_id = current_audit_being_viewed.country.id}
end
我也知道我可能只是以错误的方式思考关系,所以请随意告诉我一个更好的方法来做我想要实现的目标。
答案 0 :(得分:0)
class Question < ActiveRecord::Base
has_and_belongs_to_many :audits
has_one :detail
end
和
class Detail < ActiveRecord::Base
belongs_to :country
belongs_to :question
end
你也提到过 &#34;现在让我们解释一下问题的细节。让我们说我有细节X,Y和Z.细节X,Y和Z都与问题1和#34;相关联。其中说一个问题可以有很多细节。
但根据您在上面做出的模型声明,仅提问&#39; has_one&#39;详情。请验证。谢谢!
对于您遇到的问题,您可以尝试使用型号&#39;范围&#39;:
class Detail < ActiveRecord::Base
belongs_to :country
belongs_to :question
scope :with_country_id, -> (country_id) { where( country_id: country_id ) }
end
假设问题has_many详细信息,那么您可以: question.details.with_country_id(current_audit_being_viewed.country_id)
另外,尝试使用has_many:through。可以使设计(和更漂亮)更容易。 ;)
希望有所帮助! :)
干杯!