簡體   English   中英

如何重組這種形式來創建關聯?

[英]How to restructure this form to create association the other way around?

最初,我創建了要瀏覽的練習。 然后,我添加了針對他們記錄“ log_entries”的功能。

這適用於

  = semantic_form_for @exercise do |exercise|
    = exercise.semantic_fields_for :log_entries do |log_entry|
      = render 'log_entries/log_entry_fields', :f => log_entry
    .links
      = link_to_add_association 'Add Set', exercise, :log_entries, :partial => "log_entries/log_entry_fields", :data => {:role => "button", :icon => "plus"}
    = exercise.buttons do
      = exercise.commit_button "Apply", :button_html => {:data => {:icon => "check", :theme => "b"}}
      = link_to "Cancel", "", :data => {:rel => "back", :icon => "delete", :role => "button", :theme => "a"}

我現在添加了要求它與用戶關聯的要求。 我不確定如何以最佳方式做到這一點。 這是張貼在運動控制器現在,和運動是不是真的與用戶關聯。 所以在運動控制器,我可以合並的參數,可以,但似乎的hackish。

正確的方法是通過用戶創建日志條目關聯,對嗎? 但是,我將如何重組表格以使其正常工作?

我可能不應該再為此使用運動控制器,因為它正在創建log_entries,然后可以在LogEntryController中通過該位置設置用戶...但是執行此操作的最佳方法是什么? 由於某種原因,我無法弄清楚如何將鍛煉傳遞給log_entries控制器,然后使集合以如圖所示的形式呈現。

也許我整天不去編碼。 謝謝!

我將Cocoon庫用於添加關聯功能。

您不需要寶石即可完成此任務。 考慮以下關聯:

class User < ActiveRecord::Base
  has_many :log_entries
end

class Exercise < ActiveRecord::Base
  has_many :log_entries
end

class LogEntry < ActiveRecord::Base
  belongs_to :user
  belongs_to :exercise
end

以及以下深層嵌套的路線:

YourApp::Application.routes.draw do
  resources :users do
    resources :exercises do
      resources :log_entries
    end
  end
end

這將導致一個新的鏈接看起來像這樣(很長,我知道):

<%= link_to new_user_exercise_log_entry_path(user, exercise) %>

其中userexerciselog_entry所屬的用戶和演習對象。 URI的資源部分看起來像這樣,例如:

/users/1/exercises/1/log_entries/new

請注意,您應該提交的是log_entry表單,而不是練習表單。

而且您不必對log_entry表單做任何特殊的事情。 由於模型之間存在關系並且路由是嵌套的,因此您只需在log_entry控制器操作中訪問params[:user_id]params[:exercise_id] ,然后將它們分配給新的log_entry對象即可。

暫無
暫無

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

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