Rails 3 关联存在的错误检查
我有一个模型“modela”,它与模型“submodelb”有 has_many_through 关系。在控制器中,我想检查 modela 是否有任何与之关联的 submodelb。我已经尝试过下面的两个代码示例;但是,如果 modela 没有任何 submodelbs,则两者都会抛出错误“未定义方法‘submodelbs’”。请帮我看看我做错了什么。
样本1: 如果 [电子邮件受保护]?
@submodelbs = @modela.submodelbs
别的 @submodelbs = [] 结束
示例 2 : 如果 [电子邮件受保护]?
@submodelbs = @modela.submodelbs
别的 @submodelbs = [] 结尾
I has a model "modela" that has a has_many_through relationship with model "submodelb". In a controller I want to check if modela has any submodelb associated with it. I have tried the two code examples below; however, the both throw the error "undefined method `submodelbs'" if modela does not have any submodelbs. Please help me see what I am doing wrong.
Sample 1:
if [email protected]?
@submodelbs = @modela.submodelbs
else
@submodelbs = []
end
Sample 2:
if [email protected]?
@submodelbs = @modela.submodelbs
else
@submodelbs = []
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
.present?
,这与blank?
相反,但我认为您的问题是
@modela
可能是nil< /code> 或者您可能没有在模型中正确定义关联。
You can use
.present?
which is the opposite ofblank?
But I think your problem is that
@modela
may benil
or you may have not defined associations correctly in the model.由
has_many_through
生成的 reader 方法总是返回看起来像数组的内容,因此它永远不应该返回 nil。那么,你不能总是返回@modela.submodelbs
吗?The reader method produced by
has_many_through
always returns something that looks like an Array, so it should never return nil. So, can't you just return@modela.submodelbs
always?我用空白?
但错误消息表明您的关联定义可能有问题...
您想要实现的目标可以用单行代码完成。
此外,如果子模型为零,将分配空数组,那么
I use blank?
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
if submodelbs are nil empty array will be assigned.
为什么不将检查放在
begin...rescue...end
块中呢?Why not just put your checks in a
begin...rescue...end
block?