简体   繁体   English

Rails 3错误检查关联的存在

[英]Rails 3 Error Checking for Existence of Association

I has a model "modela" that has a has_many_through relationship with model "submodelb". 我有一个模型“ modela”,与模型“ submodelb”具有has_many_through关系。 In a controller I want to check if modela has any submodelb associated with it. 在控制器中,我想检查modela是否具有与之关联的任何submodelb。 I have tried the two code examples below; 我已经尝试了下面的两个代码示例; however, the both throw the error "undefined method `submodelbs'" if modela does not have any submodelbs. 但是,如果modela没有任何子模型b,则两者都将引发错误“未定义的方法'子模型bs”。 Please help me see what I am doing wrong. 请帮助我看看我在做什么错。

Sample 1: if !@modela.submodelbs.nil? 示例1:!@ modela.submodelbs.nil?
@submodelbs = @modela.submodelbs @submodelbs = @ modela.submodelbs
else @submodelbs = [] end 否则@submodelbs = []结束

Sample 2: if !@modela.submodelbs.empty? 示例2:!@ modela.submodelbs.empty是否?
@submodelbs = @modela.submodelbs @submodelbs = @ modela.submodelbs
else @submodelbs = [] end 否则@submodelbs = []结束

You can use .present? 您可以使用.present? which is the opposite of blank? 哪个与blank?相反blank?

@submodelbs = @modela.submodelbs.present? ? @modela.submodelbs : []

But I think your problem is that @modela may be nil or you may have not defined associations correctly in the model. 但是我认为您的问题是@modela可能为nil或者您可能未在模型中正确定义关联。

The reader method produced by has_many_through always returns something that looks like an Array, so it should never return nil. has_many_through生成的reader方法始终返回类似于Array的值,因此它永远不应返回nil。 So, can't you just return @modela.submodelbs always? 所以,您不能总是返回@modela.submodelbs吗?

I use blank? 我用空白吗?

unless @modela.submodelbs.blank?
   #modela has submodelbs
end

but error messege suggests that you may have something wrong with association definition... 但是错误消息提示您关联定义可能有问题...

Also what you are trying to achieve can be done with one-liner 同样,您想要实现的目标也可以使用单线完成

@modela.submodelbs ||= []

if submodelbs are nil empty array will be assigned. 如果submodelbs为nil,则将分配空数组。

为什么不只将支票放在begin...rescue...end块中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM