【发布时间】:2014-08-03 19:44:03
【问题描述】:
我在 rails 4 应用中拥有的两个模型如下:
class Council < ActiveRecord::Base
has_many :alternatives
...
end
class Alternative < ActiveRecord::Base
belongs_to :council
...
end
我正在渲染一个替代表单,它允许我从委员会的展示视图中创建一个新的替代对象:
理事会/show.html.erb
<%= render 'alternatives/form' %>
alternatives/_form.html.erb
<%= form_for(@alternative) do |f| %>
<div class="form-group">
<div>
<%= f.text_field :title, :placeholder => 'Provide your alternative', autofocus: true, class:"form-control" %>
</div>
<div>
<%= f.text_area :more_info, :placeholder => 'Describe your alternative', autofocus: true, class:"form-control", rows: '4' %>
</div>
</div>
<div>
<%= f.submit 'Submit the alternative!', class:"btn btn-success" %>
</div>
<% end %>
此时,我想将 Alternative 对象与显示视图中的特定 Council 对象相关联,如下面的代码,但未定义变量 @council:
控制器/alternatives_controller.rb
class AlternativesController < ApplicationController
before_action :set_alternative, only: [:show, :edit, :update, :destroy]
def create
@alternative = Alternative.new(alternative_params)
@alternative.council = @council
end
private
def set_alternative
@alternative = Alternative.find(params[:id])
end
def alternative_params
params.require(:alternative).permit(:title, :more_info)
end
end
这将允许我显示与某个委员会对象相关的所有备选方案:
理事会/show.html.erb
...
<% @council.alternatives.each do |alternative| %>
<%= alternative.title %>
<%= alternative.more_info %>
<% end %>
...
我已经仔细查看了 Ruby on Rails 指南 (http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference),但显然我遗漏了一些东西。有任何想法吗?谢谢。
【问题讨论】:
标签: ruby-on-rails forms ruby-on-rails-4 models model-associations