我正在使用嵌套属性中的几个模型。
我有“团队”(有许多比赛)和“比赛”(属于团队)。但我也希望竞赛引用“类别”作为子对象(一个竞赛只能有一个类别,一个类别可以有多个竞赛)。
逻辑的工作方式是,首先创建团队,然后创建竞赛,然后我希望能够从类别列表(部分)中进行选择并建立关联(将竞赛中的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结束
在show视图中,我有以下代码:
<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'%>我的categories的部分_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>我感到困惑的地方是把代码放在哪里(在竞赛或类别控制器中?)用于设置类别-竞赛父子关系,以及哪个视图(竞赛显示视图或类别_index partial?)。我非常确定我在这里不理解Rails的一些基本知识,所以如果有人能给我指点一下文档,可能会澄清我的困惑,我将非常感激。
发布于 2012-07-13 03:13:17
好吧,这就是我是如何解决我的问题的(以防后来有人找到它,并使用我尝试过的相同搜索词):
型号:
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
endCategories view (_index)是竞赛/展示视图中的一部分,它包含以下三段代码:
<table>
<% @categories.each do |category| %>
<tr>
<td><%= form_for [category, @contest] do |f| %>
<% f.submit "Select" %>
<% end %></td>
</tr>
<%end%>
</table>这就是将属于另一个父项的记录与不同模型中的另一个父项相关联所需的内容(在创建第一个关系之后)。
https://stackoverflow.com/questions/11333655
复制相似问题