2011-06-21 3 views
0

次のコードは、すべてのおすすめイベントと、これらのすべての関連イメージを私のビューの中に表示します。 各イベントの最初の画像を表示する方法を知りたいのですが、含まれているモデルの最初の結果を表示する、RoR3

# event model 
class Event < ActiveRecord::Base 
    attr_accessible :title, :start_date, :end_date, :content, :is_featured, :assets_attributes 
    has_many :assets, :order => 'asset_order ASC' 
    accepts_nested_attributes_for :assets, :allow_destroy => true 
end 

# asset model 
class Asset < ActiveRecord::Base 
    belongs_to :event 
    belongs_to :static 
    has_attached_file :asset, :styles => { :large => "660x270#", :medium => "300x300#", :thumb => "100x100#" } 
end 

# event model 
class Event < ActiveRecord::Base 
    attr_accessible :title, :start_date, :end_date, :content, :is_featured,    :assets_attributes 
    has_many :assets, :order => 'asset_order ASC' 
    accepts_nested_attributes_for :assets, :allow_destroy => true 
end 

# static controller  
def show 
    @events = Event.where(:is_featured => 1).includes(:assets) 
    @static = Static.where(:id => params[:id]).first 
    ... 
end 

# static show view 
- @events.each do |event| 
    - event.assets.each do |asset| 
    =image_tag asset.asset.url(:medium) 
    = event.title 
    = event.start_date.to_date 

答えて

0

このようなものをお探しですか?

# static show view 
- @events.each_with_index do |event, index| 
    - event.assets.each do |asset| 
    =image_tag asset.asset.url(:medium) unless index > 0 
    = event.title 
    = event.start_date.to_date 
+0

これは機能していますが、私のコントローラーがすべての画像を取得していますが、私が必要なときには、表示が間違った場所のように見えます。 –

+0

ああ、あなたが今欲しいものを理解しています。ただし、実際には、コントローラはDB側の単純な結合を含む関連するAssetインスタンスへの参照のみを取得していることに注意してください。テーブルを適切に索引付けしておけば、実行しようとしている間のオーバーヘッドの違いと、この解決方法は、ユーザーやヒープにとっては無視できないほど顕著になります。それ以外の場合は、そのアセットを持つ最初のイベントをプルし、そのアセットと最初のイベントのIDを除く、残りのイベントを照会します。例が必要な場合は教えてください。 – Midwire

関連する問題