accepts_nested_attributes_for:我做错了什么 [英] accepts_nested_attributes_for: What am I doing wrong
问题描述
我尝试在 rails4 中创建一对多连接.但是,虽然我没有收到错误消息,但未存储嵌套属性.
我做错了什么?
站模型
class Station
地址模型
类地址
站控制器类 StationsController <应用控制器
def new@station = Station.new@station.addresses.build结尾定义创建@station = Station.new(station_params)@station.save重定向到@station结尾定义索引@stations = Station.all结尾私人的def station_paramsparams.require(:station).permit(:name, adresses_attributes: [:url])结尾结尾
站:new.html.erb
<%= form_for :station, url:station_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>
<%结束%><p><%= station.submit %></p><%结束%>
我构建了这个问题的一个最小示例,并将其记录为此处的分步说明:https://groups.google.com/forum/#!topic/rubyonrails-talk/4RF_CFChua0
你应该使用 form_for @station
而不是 form_for :station
(使用实例而不是符号).
干杯
I try do create a one-to-many connection in 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
class Adress < ActiveRecord::Base
belongs_to :station
end
Station-Controller class 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
<%= 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
You should use form_for @station
instead of form_for :station
(use an instance instead of a symbol).
Cheers
这篇关于accepts_nested_attributes_for:我做错了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!