使用此代码获取我的链接以向我显示3个数据库条目作为表中的链接我得到nil的未定义方法“+”:对于没有这些字段的公司,NilClass错误此错误。
<td><%= link_to @company.office_adress_street + ", " + @company.office_adress_city + ", " + @company.office_adress_postcode, "http://maps.google.com/?q=" + @company.office_adress_street + ", " + @company.office_adress_city + ", " + @company.office_adress_postcode, :target => '_blank' %></td>
答案 0 :(得分:4)
您应该检查每个对@ company.XXX属性的调用是否都不返回nil,更好的字符串连接应该是这样的结构:
"#{link_to(@company.office_adress_street)}, #{@company.office_adress_city}, #{@company.office_adress_postcode}"
答案 1 :(得分:3)
我建议你为你的模型(或装饰者)添加一个方法
def address
[office_address_street, office_address_city, office_address_postcode].compact.join(', ')
end
然后在你看来:
<td><%= link_to @company.address, "http://maps.google.com/?q=" + @company.address, :target => '_blank' %></td>
如果您决定使用装饰器,您还可以创建一个返回链接的方法link_to_address
,然后将视图简化为:
<td><%= @company.link_to_address %></td>
答案 2 :(得分:1)
确保@company
具有office_adress_street
属性(等等)并且它不是nil
(期望@company.office_adress_street
成为字符串)
也许有拼写错误? adress
或address
?
如果@company
有时没有office_adress_street
属性,请使用link_to_if帮助:
<td><%= link_to_if @company.office_adress_street, @company.office_adress_street + ", " + @company.office_adress_city + ", " + @company.office_adress_postcode, "http://maps.google.com/?q=" + @company.office_adress_street + ", " + @company.office_adress_city + ", " + @company.office_adress_postcode, :target => '_blank' %></td>