MAC
MAC

Reputation: 686

How to save data in rails with no form?

I am new to rails and I am just learning the basics. This is my code on saving data:

app/controllers/employee_controller.rb

 class EmployeesController < ApplicationController

    def index
      render json: @employees = Employee.all
    end

    def show
      render json: @employee = Employee.find(params[:id])
    end

    def new
      @employee = Employee.new
    end

    def create
       @employee = Employee.new(employee_params)

      @employee.save
      redirect_to @employee
    end

    private
       def employee_params
         params.require(:employee).permit(:fname, :mname, :lname, :contactno, :address, :username, :password)
       end
 end

app/views/employees/new.html.erb

<%= form_for @employee do |f| %>
<p>
  <label>First Name</label><br>
  <%= f.text_field :fname %>
</p>
<p>
  <label>Middle Name</label><br>
  <%= f.text_field :mname %>
</p>
<p>
  <label>Last Name</label><br>
  <%= f.text_field :lname %>
</p>
<p>
  <label>Contact No.</label><br>
  <%= f.text_field :contactno %>
</p>
<p>
  <label>Address</label><br>
  <%= f.text_area :address %>
</p>
<br>
<p>
  <label>Username</label><br>
  <%= f.text_field :username %>
</p>
<p>
  <label>Password</label><br>
  <%= f.text_field :password %>
</p>
<br>

<p>
  <%= f.submit %>
</p>

But, my goal is to save right away without the html form. (NO INPUT) Like when I visit a certain URL and the values are automatically saved in the database.
For a start, I would like to assign a constant value in every field just to see how it works.

Example,

How can I assign those values right away after a certain URL/site is visited.

Upvotes: 0

Views: 1380

Answers (2)

cappie013
cappie013

Reputation: 2444

You start by adding a method to your controller

def update_fname
    # get the parameters
    fname = params[:fname]

    # get the employee ID
    id = params[:id]

    # find the employee
    @employee = Employee.find(id)

    # update the employee
    employee.update_attributes(fname: fname)

    redirect_to @employee
end

Then, in your route, you add:

resources :employees do 
    get 'update_fname'
end

And you call the route, who should be http://localhost:3000/employees/{:id}/update_fname?fname={your_fname}

Upvotes: 2

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

In your controller try something like:

class EmployeesController < ApplicationController

  def custom
    @employee = Employee.create(fname: "sample name")
  end
end

and define proper route in config/routes.rb:

get "/custom" => "employees#custom"

When you enter proper url in your browser, like:

localhost:3000/custom

The Employee should be saved.

Good luck!

Upvotes: 1

Related Questions