Search code examples
ruby-on-railsrubydatabasecontrollers

Create item in Ruby DB through form submission


I'm new to Ruby and back-end programming, and am trying to build my first app. What I'm trying to do is create an HTML form that stores the submitted data into a database. I have everything finished, and when I click the submit button on my form it triggers the correct controller, but I'm hitting this error:

NameError in SubmissionsController#create

undefined local variable or method `title' for # Rails.root: /home/tom/brain_db

Application Trace | Framework Trace | Full Trace app/controllers/submissions_controller.rb:4:in `create' Request

Parameters:

{"title"=>"fsdf", "content"=>"fsdfsd"}

And here is my SubmissionsController:

class SubmissionsController < ApplicationController

def create 
    Submission.where(title: title).first_or_create(
        title: title,
        content: title
        )
end

def index
    render json: Submission.all
end

def show 
    render json: Submission.find(params[:id])
end


end

The problem is that I don't know how to connect my "create" action with the submitted data. The data is correctly sending the back-end in JSON, and in the create action if I changed where(title: title) to where(title: "title") and so on it saves the item into the database properly, but obviously I want to be saving the data from the form. Any advice on this for a Ruby novice?


Solution

  • Data of the submitted form is accessible in the params "hash" inside the controller:

    def create 
        Submission.where(title: params[:title]).first_or_create(
            title: params[:title],
            content: params[:content]
            )
    end