2016-09-02 5 views
0

を注文します。

stories_controller.rbは次のようになります。それらの両方を注文する私のindex.html.erbイムtryignでルビー - 私はそれらを一緒に注文しようとしています私は2つのモデルのimage.rbとstory.rb <br></p> <p>を持つ2つのモデル

private 
    def image_params 
     params.require(:image).permit(:title, :image, :image_file_name, :category) 
    end 

しかし、私はに実行します。

def index 
    @stories = Story.all.order(:cached_votes_total => :desc) 
    @images = Image.all.order(:cached_votes_total => :desc) 
    @combined = (@stories + @images).sort_by {|record| record.created_at} 
end 


private 
    def story_params 
     params.require(:story).permit(:title, :content, :category) 
    end 


images_controller.rbは次のようになりますパラメータが異なるため、未定義のメソッドエラーが発生します。

<% @combined.each do |s| %> 
    ...   
<% end %> 

これを修正する方法はありますか?

+0

これは間違ったアプローチです。モデルの関連付けを使用する必要があります –

答えて

0

これは、2つのモデルを組み合わせることで、間違ったアプローチであるが、推奨されていない、あなたは、コントローラは、この..例えば

# Image Model 
class Image < ActiveRecord::Base 
    belongs_to :story 
end 

# Image Model 
class Story < ActiveRecord::Base 
    has_one :image 
end 

ためのモデルの関連付けを使用する必要があります。..

def index 
    @stories = Story.find(:all, :include => :image).order(:cached_votes_total => :desc) 
end 

最後にビューで

<% @stories.each do |story| %> 

# here you can access story and story.image 
    ...   
<% end %> 
+0

私の移行ではcreate_storiesとcreate_imagesがあるので、create_table:imagesをcreate_stories移行ファイルに追加する必要がありますか?ここでは未知の列 'images.story_id'を 'where節'に返します:SELECT 'images' * FROM' images' WHERE 'images'.story_id' IN( '7'、 '8') –

+0

ここでの関連付けについて学んでくださいhttp://guides.rubyonrails.org/association_basics.html –

関連する問題