gpt4 book ai didi

ruby-on-rails - accepts_nested_attributes_for : What am I doing wrong

转载 作者:行者123 更新时间:2023-12-04 16:45:09 25 4
gpt4 key购买 nike

我尝试在 rails4 中创建一对多连接。但是,虽然我没有收到错误消息,但未存储嵌套属性。

我究竟做错了什么?

站型

class Station < ActiveRecord::Base
has_many :adresses

accepts_nested_attributes_for :adresses
end

地址-型号
    class Adress < ActiveRecord::Base
belongs_to :station
end

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

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

[编辑]
我构建了这个问题的最小示例,并将其记录为此处的分步说明: 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

我仍在尝试为此找到官方文档:(

关于ruby-on-rails - accepts_nested_attributes_for : What am I doing wrong,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17558309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com