2014-02-14 55 views
1

我正試圖在rails中的兩個模型之間構建一個'ajaxy'表單。這裏有相關的文件和代碼片段...與連接表關聯的Rails ajax表單

我的模型

ActiveRecord::Schema.define(:version => 20140214134314) do 

    create_table "group_shots", :force => true do |t| 
    t.integer "shot_id" 
    t.integer "group_id" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    end 

    create_table "groups", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    end 

    create_table "shots", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    end 

end 

應用程序/視圖/組/ show.html.erb

<b>Name:</b> 
    <%= @group.name %> 
<%= link_to 'New Shot', new_shot_path, id: "new_shot", remote: true %></br> 

應用程序/視圖/張/新。 js.erb

$('#new_shot').hide().after('<%= j render("form") %>'); 

應用程序/控制器/ shots_controller.rb

def create 
    @shot = Shot.new(params[:shot]) 

    respond_to do |format| 
     if @shot.save 
     GroupShot.create! :shot_id => @shot.id 

def new 
    @shot = Shot.new 
end 

我的最終目標是當用戶正在查看一個組(顯示操作/視圖)時,他們可以添加與該組關聯的鏡頭,因此當用戶添加鏡頭時,正確的條目將在group_shot表。

您可以在鏡頭控制器中看到鏡頭保存時,我正在成功創建組/鏡頭表中的新條目。我得到了shot_id,但不是group_id。所以這是一個問題,我怎麼在這個視圖/控制器中獲取group_id。任何幫助讚賞。

回答

0

我的建議是通過GROUP_ID作爲參數調用您的groups_controller#秀以new_shot_path:

new_shot_path(group_id: @group) 

則包括其作爲形式的隱藏字段您使用的是您的shots_controller #新觀點,採用hidden_​​field_tag:

<%= hidden_field_tag 'group_id', @group.id %> 

,然後將其包含在您的來電GroupShot#創建在shots_controller#創建方法:

GroupShot.create! :shot_id => @shot.id, :group_id => params[:group_id] 

請記住,您在shots_controller#create中做了兩件事 - 創建鏡頭並將其關聯回組,這可能有點不正統。從你的代碼看來,如果沒有相關的組,就不會創建Shot。如果您的出發點始終是查看組(然後向所選組添加鏡頭),那麼您可能需要考慮將其作爲像#add_shot之類的groups_controller,但這取決於應用程序的其餘部分是如何構建的。

+0

良好的編輯,veritas1 - 謝謝! –

+0

謝謝你們,我不會這樣做。注意,雖然在組視圖中,所有的邏輯都發生在shots_controller中,但是導致ajax/partials被調用的地方。該組已經創建,我只需要以某種方式獲得該ID。 – Lumbee

+0

然後我想你必須把它作爲參數傳遞給group/show.html中的new_shot_path - 'new_shot_path(group_id:@group)'。但我相信如果你這樣做,你將不得不修改路線來識別參數。 –