私は投稿モデルとカテゴリーモデルを持っています
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'