lundi 7 mars 2016

How would someone list a all objects that have a certain value in Ruby on Rails?

I'm working on building a page that will list off all of the models that contain the value of '1' for :category_id, here's the snippet from the page it's self

<h1>Discover the best of Games</h1>
<p>These are games we have featured and awarded</p>
<% @posts.find_by(category_id: 1) do |post| %>
  <h2>
    <%= link_to post.title, post %>
  </h2>
<% end %>

Notice the @posts.find_by(category_id: 1) do |post| is obviously wrong. It isn't displaying any posts and it comes up with the error of undefined methodfind_by' for nil:NilClass` So yes, I know .find_by is not correct. That much is obvious.

Here's the snippets from Schema.rb and post_controller.rb

Schema

  create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "category_id"
  end

  add_index "posts", ["category_id"], name: "index_posts_on_category_id"

Posts_controller (whole thing)

class PostsController < ApplicationController
    before_action :find_post, only: [:show, :edit, :update, :destroy]

    def index
        @posts = Post.all.order("created_at DESC")
    end

    def show
    end

    def new
        @post = Post.new
    end

    def create
        @post = Post.new(post_params)

        if @post.save
          redirect_to @post, notice: "Successfully created"
        else
          render 'new'
        end
    end

    def edit
    end

    def update
        if @post.update(post_params)
            redirect_to @post, notice: "Post was successfully updated"
        else
            render 'edit'
        end
    end

    def destroy
        @post.destroy
        redirect_to root_path
    end

    private

    def post_params
        params.require(:post).permit(:title, :description, :category_id)
    end

    def find_post
        @post = Post.find(params[:id])
    end

end

Any help would be highly appreciated as I am very new to Rails and just getting the hang of the basics. Thanks.

Aucun commentaire:

Enregistrer un commentaire