accepts_nested_attributes_for: What am I doing wro

2019-02-17 23:52发布

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

3条回答
姐就是有狂的资本
2楼-- · 2019-02-18 00:04

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

Cheers

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-18 00:09

In Rails 4, you also need to permit the id attribute for adresses. 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 :(

查看更多
等我变得足够好
4楼-- · 2019-02-18 00:11

in the StationController class, I would do :

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
查看更多
登录 后发表回答