The posts and categories are not agreeing on something and I'm not sure what it is. What am I doing wrong?
As soon as I click a category nothing changes but the url to http://localhost:3000/posts?category=Physics
class Post < ActiveRecord::Base
belongs_to :category
# ...
end
class Category < ActiveRecord::Base
belongs_to :posts
# ...
end
Here is the Posts Controller:
class PostsController < ApplicationController
def index
if
params[:category_id].blank?
@posts = Post.all.order("created_at DESC")
else
@category_id = Category.find_by(name: params[:category]).id
@posts = Post.where(category_id: @category_id).order("created_at DESC")
end
end
# ...
def post_params
params.require(:post).permit(:title, :link, :description, :category_id)
end
Here is the index file:
<% Category.all.each do |category| %>
<%= link_to category.name, posts_path(category: category.name) %>
<% end %>
<% @posts.each do |post| %>
<%= link_to post.title, post %>
<%= link_to time_ago_in_words(post.created_at) + " ago", post %>
<% end %>
This is the migration for Posts:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.string :link
t.text :description
t.timestamps null: false
end
end
end
This is the migration for AddIdToPosts
class AddIdToPosts < ActiveRecord::Migration
def change
add_column :posts, :category_id, :integer
end
end
This is what console told me about the last post:
irb(main):008:0> Category
=> Category(id: integer, name: string, created_at: datetime, updated_at: datetime)
irb(main):009:0> @post = Post.last
Post Load (17.0ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT 1
=> #<Post id: 3, title: "Testing", link: "",
description: "testing", created_at: "2015-05-06 07:08:36",
updated_at: "2015-05-06 07:08:36", user_id: 1, category_id: 1>
Aucun commentaire:
Enregistrer un commentaire