我尝试在rails4中创建一对多连接。但是,虽然我没有收到错误,但嵌套属性未存储。
我究竟做错了什么?
车站模型
class Station < ActiveRecord::Base
has_many :adresses
accepts_nested_attributes_for :adresses
end
地址模型
class Adress < ActiveRecord::Base
belongs_to :station
end
站控制器类 StationsController
def new
@station = Station.new
@station.adresses.build
end
def create
@station = Station.new(station_params)
@station.save
redirect_to @station
end
def index
@stations = Station.all
end
private
def station_params
params.require(:station).permit(:name, adresses_attributes: [ :url ])
end
end
站:new.html.erb
<%= form_for :station, url: stations_path do |station| %>
<p>
<%= station.label :name %><br />
<%= station.text_field :name %>
</p>
<%= station.fields_for :adresses do |adress| %>
<div class="field">
<p>
<%= adress.label :url %><br />
<%= adress.text_field :url %>
</p>
</div>
<% end %>
<p>
<%= station.submit %>
</p>
<% end %>
[edit]
我构建了这个问题的最小示例,并将其记录为分步说明:https://groups.google.com/forum/#!topic/rubyonrails-talk/4RF_CFChua0
在 Rails 4 中,您还需要允许id
属性为adresses
。请这样做:
def station_params
params.require(:station).permit(:name, adresses_attributes: [ :url, :id ])
end
我仍在尝试找到这方面的官方文档:(
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)