【发布时间】: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