Ruby on rails 如何重新构造此表单以创建相反的关联?

Ruby on rails 如何重新构造此表单以创建相反的关联?,ruby-on-rails,forms,associations,Ruby On Rails,Forms,Associations,最初,我创建了浏览练习。然后,我添加了针对它们记录“log_条目”的功能 这是有效的 = 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_a

最初,我创建了浏览练习。然后,我添加了针对它们记录“log_条目”的功能

这是有效的

  = 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"}
现在,我添加了需要将其与用户关联的需求。我不知道如何以最好的方式做到这一点。这是现在发布到练习控制器的,并且练习实际上与用户没有关联。因此,在运动控制器中,我可以将参数合并到中,但这似乎有点骇人听闻

正确的方法是通过用户创建日志条目关联,对吗?但是我该如何重组表单以使其生效呢

我可能也不应该再使用exercise控制器了,因为它正在创建log_条目,然后在LogEntryController中,用户可以在那里进行设置。。。但是最好的方法是什么呢?由于某些原因,我无法确定如何将训练传递到log_entries控制器,然后以如图所示的形式呈现集合

也许我整天都在编代码,脑子都快坏了。谢谢


我正在使用库来添加关联功能。

您不需要gem来完成此操作。考虑下面的关联:

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
这将导致一个新的链接看起来像这样(很长,我知道):

请注意,您应该提交的是日志输入表单,而不是练习表单


你不必对你的登录表做任何特殊的处理。由于模型之间存在关系,并且路由是嵌套的,因此您只需访问
log\u条目
控制器操作中的
params[:user\u id]
params[:exercise\u id]
,然后将它们分配给新的
log\u条目
对象

我意识到我甚至不能通过exercisecontroller设置用户,因为我必须迭代日志项的集合,而为每个日志项添加一个user_id是很糟糕的。那么,如何反过来做呢?通过log_entries controller创建集合,并在其中设置用户和练习?这取决于您希望用户的行为:您希望能够将这些
log_条目
分配给用户,还是希望将它们分配给登录用户。对于第一个用例,请参见Anxity的答案。对于第二个用例,您应该根据
当前用户
(如果您使用Desive)或其他内容将用户分配到日志项,但您不希望通过REST-path来完成。您好,谢谢。所以,我想知道你是否能帮我更进一步。这开始变得更有意义了。问题是我在一个表单中添加了多个日志条目(使用cocoon)。那么使用上面的例子,我将如何在表单状态下执行它呢?例如:semantic_form_for[user,exercise](日志条目如何放入该路径?)我可以用[current_user,ew.exercise]do | exercise |和yadayadada来完成它,Yadayadadada去exercise | controller并执行这个`params[:exercise][:log_entries|属性]。每个do | value | value[1]。合并!(:user\u id=>current\u user.id)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) %>
/users/1/exercises/1/log_entries/new