我正試圖在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。任何幫助讚賞。
良好的編輯,veritas1 - 謝謝! –
謝謝你們,我不會這樣做。注意,雖然在組視圖中,所有的邏輯都發生在shots_controller中,但是導致ajax/partials被調用的地方。該組已經創建,我只需要以某種方式獲得該ID。 – Lumbee
然後我想你必須把它作爲參數傳遞給group/show.html中的new_shot_path - 'new_shot_path(group_id:@group)'。但我相信如果你這樣做,你將不得不修改路線來識別參數。 –