如何以相同的形式更新表及其关联的连接表?

问题描述 投票:0回答:1

我正在为播客建立一个网站。我的表是“剧集”和“来宾”以及名为“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输入到表单中,单击更新按钮,并让与该剧集相关联的访客更新。

ruby-on-rails forms jointable
1个回答
0
投票

给这个手表一试。 http://railscasts.com/episodes/17-habtm-checkboxes-revised?autoplay=true

它应该解决你的问题。我也建议做has_many_through而不是has_and_belongs_to_many,因为它更灵活。视频也谈到了这一点。

您可以按如下方式构建数据:Guests通过Appearances有许多EpisodesEpisodesGuests有反向。

这会让你查看Guest.first.appearances,看看史蒂夫出现在3集中,或者打电话给Episode.third.guests,看看史蒂夫,苏西和艾哈迈德都在这一集中。

© www.soinside.com 2019 - 2024. All rights reserved.