[英]accepts_nested_attributes_for: What am I doing wrong
I try do create a one-to-many connection in rails4. 我尝试在rails4中创建一对多连接。 However, although I don't get an error, the nested attribute is not stored.
但是,虽然我没有收到错误,但不存储嵌套属性。
What am I doing wrong? 我究竟做错了什么?
Station-Models 站的模型
class Station < ActiveRecord::Base
has_many :adresses
accepts_nested_attributes_for :adresses
end
Adress-Model ADRESS-型号
class Adress < ActiveRecord::Base
belongs_to :station
end
Station-Controller class StationsController < ApplicationController Station-Controller类StationsController <ApplicationController
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
Station: new.html.erb 站: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] [编辑]
I constructed a minimal example of this problem and documented it as a step-by-step instruction here: https://groups.google.com/forum/#!topic/rubyonrails-talk/4RF_CFChua0 我构建了一个这个问题的最小示例,并将其记录为此处的逐步说明: https : //groups.google.com/forum/#!topic / rubyonrails -totra / 4RF_CFChua0
In Rails 4, you also need to permit the id
attribute for adresses
. 在Rails 4中,您还需要允许
adresses
的id
属性。 Please do this: 请这样做:
def station_params
params.require(:station).permit(:name, adresses_attributes: [ :url, :id ])
end
I'm still trying to find the official documentation for this :( 我还在努力找到这个官方文档:(
You should use form_for @station
instead of form_for :station
(use an instance instead of a symbol). 您应该使用
form_for @station
而不是form_for :station
(使用实例而不是符号)。
Cheers 干杯
in the StationController class, I would do : 在StationController类中,我会这样做:
def create
@station = Station.new
@station.update_attributes(station_params)
redirect_to @station
end
instead of : 代替 :
def create
@station = Station.new(station_params)
@station.save
redirect_to @station
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.