簡體   English   中英

accepts_nested_attributes_for:我做錯了什么

[英]accepts_nested_attributes_for: What am I doing wrong

我嘗試在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

<%= 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 / ruby​​onrails -totra / 4RF_CFChua0

在Rails 4中,您還需要允許adressesid屬性。 請這樣做:

def station_params
    params.require(:station).permit(:name, adresses_attributes: [ :url, :id ])
end

我還在努力找到這個官方文檔:(

您應該使用form_for @station而不是form_for :station (使用實例而不是符號)。

干杯

在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM