[英]Associate Pre-existing Record with Pre-Existing Parent (2 parent objects)
我在使用的嵌套屬性中有多個模型。
我有“團隊”(有很多常駐隊)和“比賽”(屬於團隊)。 但我也希望比賽將“類別”作為子對象引用(比賽只能有一個類別,一個類別可以有可能有比賽)。
邏輯的工作方式是先創建一個團隊,然后創建一個競賽,然后我希望能夠從類別列表中選擇(部分)並建立關聯(將競賽中的category_id設置為id類別中的值)。 對我來說,在以團隊成員的身份創建新比賽時如何做到這一點很有意義,但是在創建第二種關系(現有比賽與現有父類別的比賽)時,我卻碰壁了。
為我顯示比賽競賽視圖的控制器為:
def show
@team = Team.find(params[:team_id])
@contest = Contest.find(params[:id])
@categories = Category.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: [@contest] }
end
結束
在顯示視圖中,我有以下代碼:
<p><b>Name:</b><%= @contest.name %></p>
<%= link_to 'Edit', edit_team_contest_path(@team, @contest) %> |
<%= link_to 'Back', team_contests_path %>
<br />
<%= render 'categories/index'%>
我對類別的部分_index包含以下代碼:
<table>
<% @categories.each do |category| %>
<tr>
<td><%= category.level1 %></td>
<td><%= category.level2 %></td>
<td><%= category.level3 %></td>
<td><%= category.level4 %></td>
<td><%= link_to 'Show', category %></td>
<td><%= link_to 'Edit', edit_category_path(category) %></td>
<td><%= link_to 'Destroy', category, confirm: 'Are you sure?', method: :delete %></td>
<%end%>
</table>
我如此困惑的地方是在哪里放置用於設置category-contest父子關系的代碼(在Contest或Category控制器中?)以及哪個視圖(Contest show視圖或Category _index部分?)。 我可以肯定的是,我對這里的Rails基本概念並不了解,因此,如果有人能指出我可能會清除我困惑的文檔,我將非常感謝。
好的,這就是我最終解決問題的方式(以防萬一以后有人找到它並使用與我嘗試的搜索詞相同的搜索詞):
楷模:
team.rb
has_many :contests, :dependent => :destroy
category.rb
has_many :contests
contest.rb
belongs_to :team, :foreign_key => "team_id"
belongs_to :category, :class_name => 'Category', :foreign_key =>"category_id"
accepts_nested_attributes_for :category
控制器:
contests_controller
def update
@contest = Contest.find(params[:id])
@team = @contest.team
if !params[:category_id].nil?
@category = Category.find(params[:category_id])
@contest.update_attributes(:category_id => @category.id)
end
respond_to do |format|
if @contest.update_attributes(params[:contest])
blah
else
blah
end
end
end
類別視圖(_index)是競賽/表演視圖的一部分,包括以下三位代碼:
<table>
<% @categories.each do |category| %>
<tr>
<td><%= form_for [category, @contest] do |f| %>
<% f.submit "Select" %>
<% end %></td>
</tr>
<%end%>
</table>
這就是將屬於另一個父級的記錄與另一個模型中的另一個父級相關聯的過程(在創建第一個關系之后)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.