0

在完成了许多 Rails 教程之后,这是我的第一个个人项目

我有两个模型,一个控制顶级记录(lesson.rb),另一个通过carrierWave(attachment.rb)控制相关图像。我正在尝试遍历链接的图像并将它们与帖子一起显示。

到目前为止,我有资产创建工作,但我很难弄清楚如何在 show.html.erb 中显示连接的图像。如果答案很愚蠢,请原谅我,我在谷歌上广泛搜索了这个,虽然我发现了很多结果,但我仍然很难将这些方法应用到我的项目中。

在此先感谢您的帮助。

/models/lesson.rb

class Lesson < ActiveRecord::Base
  attr_accessible :content, :title, :attachments_attributes

  has_many :attachments, :dependent => :destroy


  accepts_nested_attributes_for :attachments

  validates :title, :content, :presence => true
  validates :title, :uniqueness => true

end

/models/attachment.rb

class Attachment < ActiveRecord::Base
  attr_accessible :image
  belongs_to :lesson
  mount_uploader :image, ImageUploader
end

/controllers/lessons.rb(显示方法)

  def show
    @lesson = Lesson.find(params[:id])
  end

/views/lessons/show.html.erb

<div class="body sixteen columns">
    <h2><%= @lesson.title %></h2>

    <div class="sixteen columns images">
        <% for image in @lesson.attachment %>
            <%= image_tag @lesson.attachment.image_url.to_s %>
        <% end %>
    </div>

    <p><%= simple_format(@lesson.content) %></p>
</div>
4

1 回答 1

0

两件事:用于each遍历附件,并使用attachments复数而不是单数。

<% @lesson.attachments.each do |attachment| %>
  <%= image_tag attachment.image_url.to_s %>
<% end>

另一件好事是:

@lesson = Lesson.includes(:attachments).find(params[:id])

如果您includes在从数据库中检索课程时使用,它只会触发一个 SQL SELECT 查询,而不是一个 + 该课程的附件数。有关详细信息,请参阅http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations 。

于 2013-06-28T22:45:29.243 回答