如何在Rails表单中定义嵌套关联?

时间:2012-10-05 00:47:38

标签: ruby-on-rails forms activerecord scope

我使用Formtastic获得以下代码。

- if can? :update, @workout
  = semantic_form_for ew.exercise, :url => user_exercise_path(@user, ew.exercise) do |exercise|
    %table
      %thead
        %tr
          %th.reps Reps
          %th.weight Weight
      %tbody
        = exercise.semantic_fields_for :log_entries do |log_entry|
          = render 'log_entry_fields', :f => log_entry
    .links
      = link_to_add_association 'Add Set', exercise, :log_entries
    = exercise.actions do
      = exercise.action :submit

鉴于此,我的问题是log_entries为与练习相关的每个日志条目呈现log_entries。

例如,如果Bob正在记录benchpress的日志条目,并且Hope正在记录benchpress的日志条目,那么使用此表单将记录那些log_entries。我想要它做的只是针对该练习的current_user的log_entries作用域。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我通过以下修改解决了这个问题:

= exercise.semantic_fields_for :log_entries, exercise.object.log_entries.for_user(@user) do |log_entry|

逗号之后的所有内容都是新的。我在log_entry.rb上创建了一个类方法,其中包含以下内容:

def self.for_user(user)
  where(:user_id => user.id)
end
相关问题