![](/img/trans.png)
[英]Rails 6: How do I remove a record, associated through a join table without removing it from the associated table?
[英]How do update a table and it's associated join table in the same form?
我正在為播客建立一個網站。 我的表是“劇集”和“來賓”以及名為“episodes_guests”的連接表。 “劇集”擁有並屬於許多“客人”。 我有一個更新每集的信息的表單,我也試圖讓它更新與該劇集相關的客人(存儲在連接表中的數據),但無法弄清楚。
我已經能夠添加一個(form_for)表單字段來填充相關的訪客信息,但是當我點擊更新時這些字段不會更新連接表(我甚至不確定我是否輸出了這些信息)。
這是劇集控制器“編輯”視圖中的表格
<%= form_for(@episode) do |f| %>
<table summary="Episode form fields">
<tr>
<th> Episode ID </th>
<td><%= f.text_field(:id) %></td>
</tr>
<%= f.fields_for :guests, @episode.guests.each do |g| %>
<tr>
<!-- I am trying to add a selector for guests -->
<th>Guest: </th>
<td>
<%= g.text_area :last_name %>
</td>
</tr>
<% end %>
</table>
<div class="form-buttons">
<%= f.submit("Update Episode") %>
<% end %>
</div>
情節模型
class Episode < ApplicationRecord
has_and_belongs_to_many :guests
accepts_nested_attributes_for :guests
scope:sorted, lambda {order("episode_number ASC")}
end
來賓模型
class Guest < ApplicationRecord
has_and_belongs_to_many :episodes
scope:sorted, lambda {order("id ASC")}
end
情節控制器
class EpisodesController < ApplicationController
def edit
@episode = Episode.find(params[:id])
@guests = @episode.guests.all
end
def update
#Find a object using form parameters
@episode = Episode.find(params[:id])
@episode_guests = @episode.guests
#Update the object
if @episode.update_attributes(episode_params)
#If the save succeeds, redirect to the show actions
redirect_to(episode_path(@episode))
else
#If the save fails, redisplay the form so user can fix problems
render('edit')
end
end
private
def episode_params
params.require(:episode).permit(:id, :episode_number, :title, :guests, :file_name, :description, :date_released)
end
def guest_params
params.require(:guest).permit(:id, :guest_id, :first_name, :last_name)
end
end
訪客控制器
class GuestsController < ApplicationController
def edit
@guest = Guest.find(params[:id])
end
def update
#Find a object using form parameters
@guest = Guest.find(params[:id])
#Update the object
if @guest.update_attributes(guest_params)
#If the save succeeds, redirect to the show actions
redirect_to(guest_path(@guest))
else
#If the save fails, redisplay the form so user can fix problems
render('edit')
end
end
private
def guest_params
params.require(:guest).permit(:id, :guest_id, :first_name, :last_name)
end
end
我的希望是,我可以將客人ID輸入到表單中,單擊更新按鈕,並讓與該劇集相關聯的訪客更新。
給這個手表一試。 http://railscasts.com/episodes/17-habtm-checkboxes-revised?autoplay=true
它應該解決你的問題。 我還建議使用has_many_through
而不是has_and_belongs_to_many
因為它更靈活。 視頻也談到了這一點。
你可以組織你的數據如下: Guests
有很多Appearances
通過Episodes
和逆Episodes
給Guests
。
這可以讓你查看Guest.first.appearances
,看看史蒂夫出現在3集中,或者打電話給Episode.third.guests
,看看Steve,Susie和Ahmed都在這一集中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.