1

我似乎遇到了一个对我来说可能更明显的问题:如何从相关模型中获取某些属性以显示在视图中。

在我的应用程序中有这两种模型:

产品
product_images

我在旅途中写这篇文章并且没有可用的确切代码。但是我创建了必要的关联,以便一个产品has_manyproduct_images 和一个 product_imagebelongs_to一个产品。图像模型有一个 url、一个默认(布尔)标志,当然还有 product_id。

在产品索引视图中,我想显示该产品的默认图像。为了简单起见,让我们假设我可以展示第一张图片 - 一旦它起作用,条件应该很容易引入。

所以在我的产品索引视图中有这样的东西(再次,只是从记忆中):

@products.each do |p|
    <h3><%= p.name %></h3>
    <%= image_tag p.product_images.first.url %>
    <p><%= p.description %></p>
end

虽然只要我包含 image_tag,产品的描述和名称就可以很好地显示,但我的视图会因 NoMethodError 而中断,说明 url 是 Class Nil 中的未定义方法。为了让它更简单,我去掉了 image_tag,只是想看看打印在段落中的 url - 当然问题仍然存在。如果我只是尝试让p.product_images.first视图打印我认为是对象/模型的某种 ID 就好了,这告诉我关联本身是好的。那么为什么 Rails 认为 url 属性应该是一个方法呢?

我还检查了 rails 控制台,看看这是否是检索相关属性的正确语法。像这样(再次,从内存中 - 可能存在语法错误):

p = Product.first
=> [successful - shows the first product]
p.product_images.first
=> [successful - shows the first image model]
p.product_images.first.url
=> [successful - shows me the single attribute, the url to the image]

正如您现在所知道的那样,我对此很陌生,非常感谢您的帮助。当然,我阅读了 Rails 文档,但是 Active Record Query Guide 主要侧重于从当前模型中获取数据,而我无法找到示例应用程序中明显缺少的内容。

为什么这在控制台中有效,但在视图中无效?

4

1 回答 1

1

这可能是因为您的一个Product没有任何ProductImage.

ProductsHelper你可以通过在你喜欢的方法中添加一个方法来纠正这个问题:

def product_image(product)
    return if product.product_images.blank?

    image_url = product.product_images.first.url
    return if image_url.nil?

    image_tag(image_url).html_safe
end

然后从您的视图中调用它,如下所示:

@products.each do |p|
    <h3><%= p.name %></h3>
    <%= product_image(p) %>
    <p><%= p.description %></p>
end
于 2013-07-22T07:23:07.767 回答