显示rails连接表字段

时间:2017-04-17 19:10:14

标签: ruby-on-rails

所以我正在制作一个编辑页面,可以编辑动物和动物的所有者。有一个涉及的连接表,其中包含Animal所属的所有者。

更确切地说,说你有:

<% form_for :animal, url: animal_path(@edit_animal), method: :patch do |edit| %>
... animal labels and fields to edit go here ...
    <%= edit.fields_for :owners do |owner| %>
        <%= owner.label :name, "Name" %>
        <%= owner.text_field :name %>
    <%end%>
    <%=edit.submit 'Submit'%>
<%end%>

模型关联:

AnimalOwner < ApplicationRecord
    belongs_to :animal
    belongs_to :owner

Owner < ApplicationRecord
    has_many :animal_owners
    has_many :animals, :through => :animal_owners

Animal < ApplicationRecord
    has_many :animal_owners
    has_many :owners, :through => :animal_owners

基本上,我不确定我是否正在为连接表正确地执行表单。我还希望能够使用:value显示当前保存在数据库中的数据,但是对于连接表我该怎么做呢?

<%= owner.text_field :name, :value => what_goes_here? %>

1 个答案:

答案 0 :(得分:2)

如果您正在使用Rails方式,则不需要提及现有数据库数据的值。

<div class="one">One</div>
<div class="two">Two</div>
<div class="three">Three</div>
<div class="four">Four</div>

这应该将数据填充到上面给定的字段。另外,对于&#34; new&#34;和&#34;编辑&#34;方法。对于&#34;编辑&#34;你也可以使用&#34; PUT&#34;作为方法类型。

要使用<%= owner.text_field :name%> 代码,您还需要告知field_for模型Animal。这将允许嵌套的params被分配到accepts_nested_attributes_for :owners实例。

相关问题