accepts_nested_attributes_for:我做错了什么
我尝试在rails4中创建一对多连接。 但是,虽然我没有收到错误,但不存储嵌套属性。
我究竟做错了什么?
站的模型
class Station < ActiveRecord::Base has_many :adresses accepts_nested_attributes_for :adresses end
ADRESS-型号
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
[编辑]
我构建了此问题的最小示例,并将其作为分步说明记录在此处: https : //groups.google.com/forum/#!topic /rubyonrails -totra / 4RF_CFChua0
您应该使用form_for @station
而不是form_for :station
(使用实例而不是符号)。
干杯
在Rails 4中,您还需要允许adresses
的id
属性。 请这样做:
def station_params params.require(:station).permit(:name, adresses_attributes: [ :url, :id ]) end
我还在试图找到这个官方文档:(
在StationController类中,我会这样做:
def create @station = Station.new @station.update_attributes(station_params) redirect_to @station end
代替 :
def create @station = Station.new(station_params) @station.save redirect_to @station end