SamuraiBlue
SamuraiBlue

Reputation: 861

Rails: Update data via link_to (without view)

I'd like to update the data without form.

Although there are similar questions, they don't work for me.

Update field through link_to in Rails

link_to update (without form)

What I'd like to do is to delete data as followings;

For example, delete name and address when delete link is clicked.

id | name | address | ...
12 | aaa  | bbb     | ...

to

id | name | address | ...
12 |      |         | ...

Although I tried some, error was displayed.(such as ActionController::RoutingError)

schema

  create_table "rooms", force: :cascade do |t|
    t.string   "name"
    t.text     "address"
    ...

model

schedule.rb

class Schedule < ActiveRecord::Base
  belongs_to :user
  has_many :rooms, inverse_of: :schedule, dependent: :destroy
  accepts_nested_attributes_for :rooms, allow_destroy: true
  ...

room.rb

class Room < ActiveRecord::Base
  belongs_to :schedule, inverse_of: :rooms
  default_scope -> { order(day: :asc) }
  ...

view

I'd like to add the link in schedules/_schedule.html.erb It has the followings;

  ...
  <% schedule.rooms.each do |room| %>
  ...
    <% if room.name.present? %>
        <%= link_to "Delete", rooms_path(room, room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %>
  ...

I also tried another code as below, but they don't work.

   <%= link_to "Delete", rooms_path(room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %>

   <%= link_to "Delete", rooms_path(room) , method: :put, params: {address: nil}, data: { confirm: "You sure?"} %>

and so on.

routes.rb

...
  resources :schedules do
    resources :events
  end

  resources :schedules do
    resources :rooms
  end

  resources :rooms do
    resources :events
  end
...

rooms_controller.rb

...

def edit
  #nothing
end

def update
  @room = Room.find(params[:id])
  if @room.update(room_params)
    flash[:success] = "Room updated!"
    redirect_to itinerary_path(@room.itinerary) || current_user
  else
    render 'edit'
  end
end

def destroy
  @room = Room.find(params[:id])
  @room.destroy
  flash[:success] = "Room deleted"
  redirect_to schedule_path(@room.schedule) || current_user
end

private

  def room_params
    params.require(:room).permit(
      :id, :_destroy, :name, :address, :schedule_id, :day)
  end

...

It would be appreciated if you could give me any suggestion.

Upvotes: 1

Views: 2157

Answers (1)

Gokul
Gokul

Reputation: 3231

You need to change rooms_path to room_path.

Without params:

<%= link_to "Delete", room_path(room) , method: :put, data: { confirm: "You sure?"} %>

With params:

<%= link_to "Delete", room_path(room, room: {name: nil, address: nil}) , method: :put, data: { confirm: "You sure?"} %>

Upvotes: 3

Related Questions