2013-06-28 123 views
0

通过许多轨工作后教程,这是我的第一张个人项目轨道遍历链接的记录

Ive得到了两种型号,一种控制顶层记录(lesson.rb),并通过carrierWave(附相关图像其他控件。 RB)。我通过链接的图像试图回路上与后显示出来。

到目前为止,我有资产创建工作,但我很难搞清楚如何在show.html.erb中显示连接的图像。原谅我,如果答案是愚蠢的容易,我已经广泛地用Google搜索这一点,而我发现有很多结果IM仍然有应用的方法来我的项目很难。

在此先感谢您的帮助。

/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(show方法)

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> 

回答

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

+0

感谢,完美的工作,我还是习惯导轨方式,我想它显示。 – greyoxide