accepts_nested_attributes_for:我在做什么错 [英] accepts_nested_attributes_for: What am I doing wrong

查看:60
本文介绍了accepts_nested_attributes_for:我在做什么错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我在做什么错了?

工作站模型

class Station < ActiveRecord::Base
    has_many :adresses

    accepts_nested_attributes_for :adresses
end

地址模型

    class Adress < ActiveRecord::Base
        belongs_to :station
    end

工作站控制器 StationsController类< ApplicationController

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

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

[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

推荐答案

您应该使用form_for @station而不是form_for :station(使用实例代替符号).

You should use form_for @station instead of form_for :station (use an instance instead of a symbol).

欢呼

这篇关于accepts_nested_attributes_for:我在做什么错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆