2012-03-07 19 views
0

好了,所以我的聯想是:的Rails 3.2 - 嵌套的資源傳遞ID

Outlet -> has_many :monitorings 
Monitoring -> belongs_to :outlet 

我的路線:

resources :outlets do 
    resources :monitorings 
end 

查看:

<%= link_to new_outlet_monitoring_path(@outlet) %> 

當我點擊鏈接,日誌顯示outlet_id正確地作爲參數傳遞給新頁面。 但是,當保存監控記錄時,outlet_id變爲零。

任何幫助?

UPDATE:

# views/monitorings/_form.html.erb 

<%= form_for(@monitoring) do |f| %> 
<h2>Type of Monitoring</h2> 
<fieldset data-role="controlgroup" > 
    <div class="radio-group"> 
     <%= f.radio_button :mtype, "Full" %><%= f.label :mtype, "Full", value: "Full" %> 
     <%= f.radio_button :mtype, "Partial" %><%= f.label :mtype, "Partial", value: "Partial" %> 
     <%= f.radio_button :mtype, "None" %><%= f.label :mtype, "None", value: "None" %> 
    </div> 
</fieldset> 
<hr> 
<%= f.submit "Next Step" %> 
<% end %> 

而且控制器:

# controllers/monitoring_controller.rb 


def new 
    @monitoring = Monitoring.new 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @monitoring } 
    end 
end 

def create 
    @monitoring = Monitoring.new(params[:monitoring]) 

    respond_to do |format| 
    if @monitoring.save 
     format.html { redirect_to @monitoring, notice: 'Monitoring was successfully created.' } 
     format.json { render json: @monitoring, status: :created, location: @monitoring } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @monitoring.errors, status: :unprocessable_entity } 
    end 
    end 
end 

回答

1

這是最有可能與您正在創建的新的監測記錄方式的問題。我們能否看到您的表單和您的創建控制器操作?

+0

我已經將它添加爲原始問題的更新:) – Ammar 2012-03-07 22:15:22

+0

有兩種方法可以做到這一點。兩者都涉及到在新的控制器操作中創建插座對象。因此,添加'@outlet = Outlet.find(params [:outlet_id])'到新的動作。現在你有兩個選擇。 1:將@monitoring的聲明更改爲@monitoring = @ outlet.monitorings.new,並在您的視圖中不做任何更改。 2:單獨留下@monitoring的聲明並將form_for更改爲'form_for [@outlet,@monitoring] do | f |' – JohnColvin 2012-03-09 05:29:27

+0

我使用選項2並且未嘗試過選項1。我**認爲**它會工作,但。 – JohnColvin 2012-03-09 05:35:26