【问题标题】:How to pass one model to another Rails Associations如何将一个模型传递给另一个 Rails 协会
【发布时间】:2016-01-11 00:02:31
【问题描述】:

我已经对此进行了一段时间的研究,但我仍然不清楚如何执行我的预期操作。我觉得我可能使用了不正确的术语,所以我希望有人能指出我正确的方向。

我有一个应用程序,它有 documentstemplates,它们各自的模型。我有我的模型,所以:

class Document < ActiveRecord::Base
    belongs_to :user
    has_one :template
end

class Template < ActiveRecord::Base
 has_one :document
end

最后,

class User < ActiveRecord::Base
      has_many :templates
      has_many :documents, :through => :templates
end

我的user/documents 协会似乎运作良好。

我想设置一个工作流,用户将上传多个模板,然后在表单上为/documents/new 选择一个template,以基于该模板创建一个自定义的document。我将 template_id 作为我的文档模型中的一个字段,并打算在 documents 控制器中的新操作上使用一些按 @document.template_id = template.id 顺序的语法。当我尝试在我的documents 模型的新视图中使用f.select 时遇到了我的第一个障碍,因为我无法找到一种从列表中动态选择当前用户可用模板的方法。

我知道我在这里花了一点时间,但希望有人可以提供有用的答案和/或其他一些 SO 帖子或超出标准 Rails Association Basics 的进一步阅读,这些似乎无法满足我的需求。

【问题讨论】:

  • 看来我可以从documents/new 调用current_user.templates,但输出没有任何意义(至少对我而言):#&lt;Template::ActiveRecord_Associations_CollectionProxy:0x007fb9dfa6e8e8&gt;
  • 你能打印current_user.templates.first的输出吗?

标签: ruby-on-rails associations model-associations


【解决方案1】:

您应该在控制器中获得一组模板名称及其 id。

例如:

Rails 4 及以上

@available_templates = @user.templates.pluck(:id, :name)

Rails 3

@available_templates = @user.templates.map{|tmplt| [tmplt.name, tmplt.id]}

然后在 document/new 表单中执行以下操作

=f.select :template_id, @available_templates,
 {prompt: 'Select a template'}, {required: true}

您的document 模型应该是belongs_to :template 而不是has_many,因为您的文档实例中有template_id

【讨论】:

  • 我将@template = Template.all 添加到我的索引视图中,并且能够从所有模板(全部由同一用户创建)中获取输出,但是当我将@available_templates = @user.templates.pluck(:id, :name)(rails 4)添加到我没有输出的列表。你认为我应该改用current_user(使用设计语法)
  • 忽略,我将 user.rb 设置为 has_many :templates, :through =&gt; :documents,消除了 :through =&gt; documents 并能够在我的索引上获得正确的输出。仍然无法使 pluck 功能正常工作,但会对其进行研究 - 感谢您的洞察力
  • 是的 @user 只是为了演示,因为我不知道你的变量名。应该是current_user.templates.pluck(:id, :whetever) 如果这回答了您的问题,请将其标记为正确答案! :)
  • 您的回答对我很有效,谢谢。由于某种原因,我无法使用为 rails 4 提供的语法,因为它似乎没有选择正确的模板。我恢复到 rails 3 语法,它工作正常(甚至认为我正在使用 rails 4)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多