【问题标题】:Rails has many through not workingRails 有很多不工作
【发布时间】:2014-08-12 15:34:42
【问题描述】:

我有 3 个模型:

空缺

has_many :address_vacancies
has_many :addresses, through: :address_vacancies

地址

has_many :address_vacancies
has_many :vacancies, through: :address_vacancies

地址空缺

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 %>

【问题讨论】:

  • 您能在控制台中运行 Vacany.attribute_names 吗?
  • 你能显示更多的表单代码吗?另外,您能否确认您的AddressVacancy 模型有address_id 列?
  • @bratsche 是的,该模型确实有该列。
  • 您显示的代码 sn-p(使用 :address_id)与您在完整表单源中显示的内容不匹配(使用 :address)。哪个是抛出错误?他们似乎都不正确。 @vacancies 是否有自己的 address 属性?该协会将使@vacancies.addresses 提供地址集合。除非Vacancy 具有address 属性,否则@vacancies.address(因此,:address)将无效。并且:address_idAddressVacancy 的属性,但不是Vacancy 的属性。

标签: ruby-on-rails ruby associations has-and-belongs-to-many


【解决方案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 %>

【讨论】:

  • 所以我不能像普通的选择字段那样使用很多?
  • @Xeen,addresses 关联不是Vacancy 中的字段。它表示来自另一个表的记录集合,这些记录与Vacancy 表中的当前记录相关联。 Vacancy 记录没有一个属性表示从关联中选择的选项(除非您在Vacancy 表中显式创建这样的属性)。 has many 表示Vacancy 有很多地址,而不仅仅是一个用选择器设置的地址。
猜你喜欢
  • 2013-12-04
  • 1970-01-01
  • 2021-04-08
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 2017-04-25
相关资源
最近更新 更多