【问题标题】:Rails 3: Reload partial with second level associationRails 3:使用二级关联重新加载部分
【发布时间】:2012-01-26 03:55:16
【问题描述】:

我的应用结构如下:

class Study < ActiveRecord::Base
has_many :topics

class Topic < ActiveRecord::Base
has_many :references

我需要访问我的研究模型 (study.topic.references) 显示页面上的参考资料。但是,我需要根据(比如)主题的单选按钮选择来检索参考。因此,当用户单击某个主题时,我需要通过 AJAX 检索该特定主题的引用。

因此,我在我的 Study 模型中编写了以下方法:

class Study < ActiveRecord::Base

def self.topic_references(topic_id)
  Reference.where(:topic_id => topic_id)
end

我在我的 Study 控制器中访问上述方法显示如下:

class StudiesController < ApplicationController
   @references= Study.topic_references(params[:topic_id])

我计划有一个远程表单来访问上述方法并检索相应的引用。像这样的:

  - form_tag topic_references, :id=>"references_form", :method => 'get' do               
    = text_field_tag :topic_id, params[:topic_id], :value=>268
    = submit_tag "Get references"

作为初始测试,我传递了主题 ID 的值(上面的 268 值),但是,在视图中访问时 @references 仍然是空的。请帮助我了解我做错了什么以及如何实现这一目标?

【问题讨论】:

  • 尝试使用params[:references_form][:topic_id]而不是params[:topic_id]
  • @kishie,这给了我:当你没有预料到它时,你有一个 nil 对象!您可能期望有一个 Array 的实例。评估 nil 时发生错误。[]
  • 提交表单后会发生这种情况吗?把if params[:references_form]放在params[:references_form][:topic_id]之后
  • @kishie,你建议在哪里使用它?我在我的控制器上将上述内容用作@references= Study.topic_references(params[:references_form][:topic_id])
  • 使用Study.topic_references(params[:references_form][:topic_id]) if params[:references_form]

标签: ruby-on-rails ruby ajax ruby-on-rails-3 forms


【解决方案1】:

您还没有显示您的视图代码,但我猜这是因为where 正在返回对象集合而不是单个对象,如下所述:

.where vs find. ActiveRecord::Relation NoMethodError

在控制台中,在调试这类问题时,很容易错过输出中的括号,例如[#&lt;Reference id...]

【讨论】:

  • 我的问题是参数没有传递给方法。我需要帮助来了解我的表单是否正确指向该方法。 (这显然不是因为我得到错误数量的参数错误)
  • 帮我解决了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 2014-08-04
相关资源
最近更新 更多