0

私は投稿モデルとカテゴリーモデルを持っています

class Category < ActiveRecord::Base
  has_many :posts
  attr_accessible :name

end

Class Post < ActiveRecord::Base
 belongs_to :category
 attr_accessible :comments, :title, :category_id, :user_id, :photo

end

私がやろうとしているのは、アプリで @posts インスタンス変数を使用するときに再利用 (DRY 原則を適用) することです。どこかで混乱していると思います。各投稿には独自のカテゴリがあります。

私の見解では、すべてのカテゴリがリストされています

<% @categories.each do |c, v| %>
 <li><%= link_to c, blog_path(:name => c) %></li>
<% end %>

コントローラ

 def blog
if params[:month]
      date = Date.parse("1 #{params[:month]}")  # to get the first day of the month
      @posts = Post.where(:created_at => date..date.end_of_month)  # get posts for the month
    elsif params[:name]
      @posts = Post.where(:name => params[:name])
    else
      @posts = Post.all(:order => "created_at DESC")
end

     @latest = Post.latest_posts
     @posts_by_month = Post.all.group_by { |post| post.created_at.strftime("%B %Y") }

     #Category Section down side of page
     @categories = Category.all.group_by { |c| c.name }
end

私が達成したいのは、カテゴリをクリックすると、そのカテゴリに属する​​すべての投稿が表示され、カテゴリリンクをクリックした瞬間に表示されます

Mysql2::Error: Unknown column 'posts.name' in 'where clause': SELECT `posts`.* FROM `posts`  WHERE `posts`.`name` = 'Ruby'
4

2 に答える 2

2

あなたは簡単にそれを行うことができます

<% @categories.each do |c| %>
 <li><%= link_to c, blog_path(:category_id => c.id) %></li>
<% end %>

コントローラーで

def blog

  category_id = params[:category_id]
  @category = Category.find(category_id)
  @posts = @category.posts.order("posts.created_at DESC")

end
于 2013-08-02T12:43:14.093 に答える
1

この行を置き換える必要があります

@posts = Post.where(:name => params[:name])

category = Category.where(:name => params[:name]).first
@posts = category.posts
于 2013-08-02T12:48:04.477 に答える