Lucian Tarna
Lucian Tarna

Reputation: 1827

Ruby on Rails path understanding

I want to update an existing title and a description . My items are called todo, and the database is todos(since I generate with the generate commant) . The code that i have is edit.html.erb :

<%= form_for :session, url: todos_path(@todo), method: :patch do |f|  %>
  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.label :description %>
  <%= f.text_field :description %>
  <br />


  <%= f.submit "Create" %>

<% end %>

routes.rb:

  get "/todos", to: "todos#index"
  get "/todos/new", to: "todos#new"
  post "/todos", to: "todos#create"
  delete "/todos/delete" , to: "todos#delete"
  get "/todos/three", to: "todos#three"
  post "/todos/edit", to: "todos#edit"
  patch "/todos/edit", to: "todos#update" 

  # You can have the root of your site routed with "root"
  root 'todos#index'

and finally the controller:

  def edit
    @todo = Todo.find_by_id(params[:id])
  end

  def update
    todo = Todo.find_by_id(params[:session][:id])
    todo.update(:description,params[:session][:description])
  end

My problem is : I come from the index page with an ID and the edit function display me the item that I want, then I want to update the title and description field and to hit the f.submit button to update it. My issue is that the parameters don't come, I get todos.2 (which I guess it's the size of that :session hash ?). I do not with to use <%= button_to %> since I saw it is not needed in all tutorials . My question is where is my mistake, why don't the parameters come ?

Upvotes: 0

Views: 52

Answers (2)

Alexander Belonogov
Alexander Belonogov

Reputation: 19

Change in routes:

patch   "/todos/:id", to: "todos#update", as: "update_todo"

In form:

<%= form_for @todo, url: update_todo_path(@todo), method: :patch, do |f| %>

In controller:

def update
  @todo.update(params.require(:todo).permit(:title, :description))
  @todo.save
end

If you want to know all existing routes, you may use:

$ rake routes

It will show table like

     Prefix Verb   URI Pattern                     Controller#Action
       root GET    /                               posts#index
    sign_up GET    /sign_up(.:format)              users#new

where prefix will be you path url like 'sign_up' it is "sign_up_path" in controller/views.

Upvotes: 2

Surya
Surya

Reputation: 16002

Change routes to this:

patch "/todos/edit/:id", to: "todos#update", as: :update_todo

then form:

<%= form_for :session, url: update_todo_path(id: @todo.id), method: :patch do |f|  %>

and then controller:

def update
  todo = Todo.find(params[:id])
  todo.update_attributes(params[:session].slice(:description))
end

However, I'd recommend you to stick with the convention instead of writing and defining your own named routes for such purposes.

Upvotes: 1

Related Questions