dshevc93
dshevc93

Reputation: 141

ruby-on-rails - link with custom action on object

I have a list of objects and for each object I have 2 links - "Delete" and "Done". Like this:

1) Buy tomatoes; Delete | Done
2) Wash the car; Delete | Done

But my custom action done don't work. I need your help, how can I make my action and what code should I write in file routes.rb?

Controller:

def done
   @task = Task.where(id: params[:id])
   @task.done = true

   redirect_to "/tasks"
end

Link in view file:

<%= link_to "Done", {:controller => :tasks, :action => :done, :id => task.id}%>

Thanks!

Upvotes: 1

Views: 557

Answers (2)

backpackerhh
backpackerhh

Reputation: 2353

In your controller:

def done
  @task = Task.find(params[:id])
  @task.done = true
  @task.save! # Use the 'bang' method or check the return value
  redirect_to tasks_path
end

In routes.rb:

resources :tasks do
  get :done, on: :member
end

In your view:

<%= link_to 'Done', done_task_path(task.id) %>

Upvotes: 3

PrivateUser
PrivateUser

Reputation: 4524

You are assigning the value but not saving the data. So save the data using @task.save

def done
   @task = Task.where(id: params[:id])
   @task.done = true
   @task.save

   redirect_to "/tasks"
end

Upvotes: 3

Related Questions