我想在没有表格的情况下更新数据。
虽然有类似的问题,但它们对我不起作用。
Update field through link_to in Rails
我想要做的是删除以下数据;
例如,点击删除链接时删除name
和address
。
id | name | address | ...
12 | aaa | bbb | ...
到
id | name | address | ...
12 | | | ...
虽然我尝试了一些,但显示了错误。(例如ActionController::RoutingError
)
模式
create_table "rooms", force: :cascade do |t|
t.string "name"
t.text "address"
...
模型
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) }
...
查看
我想在schedules/_schedule.html.erb
中添加链接
它有以下几点;
...
<% schedule.rooms.each do |room| %>
...
<% if room.name.present? %>
<%= link_to "Delete", rooms_path(room, room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %>
...
我还尝试了下面的其他代码,但是他们没有工作。
<%= 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?"} %>
等等。
的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
...
如果你能给我任何建议,我将不胜感激。
答案 0 :(得分:3)
您需要将rooms_path
更改为room_path
。
<%= link_to "Delete", room_path(room) , method: :put, data: { confirm: "You sure?"} %>
<%= link_to "Delete", room_path(room, room: {name: nil, address: nil}) , method: :put, data: { confirm: "You sure?"} %>