我有3个型号:
空缺
has_many :address_vacancies
has_many :addresses, through: :address_vacancies
地址
has_many :address_vacancies
has_many :vacancies, through: :address_vacancies
AddressVacancy
belongs_to :address
belongs_to :vacancy
以我的形式使用以下代码:
<%= f.collection_select :address_id, Address.order("CREATED_AT DESC"),:id,:title, include_blank: true %>
会抛出错误:undefined method address_id'
,为什么会这样,我做错了什么?
修改
完整表格如下:
<%= form_for(@vacancy) do |f| %>
<% if @vacancy.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@vacancy.errors.count, "error") %> prohibited this vacancy from being saved:</h2>
<ul>
<% @vacancy.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :address %>
<%= f.collection_select :address, Address.order("CREATED_AT DESC"),:id,:title, include_blank: true %>
</div>
<div class="field">
<%= f.label :signup_until %><br>
<%= f.date_select :signup_until %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:1)
此:
<div class="field">
<%= f.label :address %>
<%= f.collection_select :address, Address.order("CREATED_AT DESC"),:id,:title, include_blank: true %>
</div>
由于Vacancy
没有单一的地址属性,因此在form_for @vacancy
表单(来自Vacancy
)的上下文中无效。它通过has_many
关联拥有一组地址。由于同样的原因,使用:address_id
也是无效的。
如果要编辑一个空缺的各种地址,则需要一个子表单。您在模型中使用accepts_nested_attributes_for
,在视图中使用fields_for
。
<%= form_for @vacancy do |f| %>
...
<%= f.fields_for :addresses do |af| %>
...
<!-- Here you'd render a partial or a set of inputs for this address %>
<%= af.input :street %> <!-- e.g., if there's a street attribute for Address -->
...
<% end %>
...
<% end %>