【问题标题】:Accessing the variable from another model in my controller从我的控制器中的另一个模型访问变量
【发布时间】:2013-10-27 12:32:58
【问题描述】:

所以,我想从我的报价模型中访问其中一个变量:

class Quotes < ActiveRecord::Base
  attr_accessible :quotes1, :quotes10, :quotes2, :quotes3, :quotes4, :quotes5, :quotes6, :quotes7, :quotes8, :quotes9

  attr_accessor :quotes1, :quotes10, :quotes2, :quotes3, :quotes4, :quotes5, :quotes6,   :quotes7, :quotes8, :quotes9
end

这是我的页面控制器,因为我想在views/pages/home.html.haml 中访问它:

def home
  @quotes = Quotes.find(:first, :order => "RANDOM()")
end

这是我的home.html.haml

%h2
  Client's opinions
%p
  =@quotes

1...10 中的所有这些引号都是字符串,并且具有默认值,它们不是 nil。而且我的主页上仍然没有任何内容。为什么?

【问题讨论】:

  • 我认为您的 Quote 模型已经过时了。看看Rails docs about relations。我认为您需要这样的关系:Client has_many Quotes。
  • 我不应该能够从我喜欢的任何控制器访问模型吗?对于我的主页,我没有模型,我只有一个控制器。而且我需要在我的主页中有 qoutes。 “客户意见”只是一个标题。
  • 是的,您可以在任何控制器中使用任何模型。
  • 那么,我做错了什么?

标签: ruby-on-rails ruby model controller haml


【解决方案1】:

控制器:

quotes_number = (srand % 10) + 1
@quotes = Quotes.find(:first, :order => "RANDOM()").send(:"quotes#{quote_number}")

查看:

%h2
  Client's opinions
%p
  =@quotes

【讨论】:

  • 但我希望它给我一个随机的 qoute。并且该代码不起作用,我得到未定义的方法错误。
  • 哦,你真的必须为此使用关联。所以你会有一个client 模型和quota 模型。 client has_many quotas.
  • 这不是我的申请。我跳到一半了。那么,我怎样才能让这些 qoutes 随机显示在我的主页上?
  • 现在,我得到这个错误: undefined method `quotes2' for nil:NilClass 为什么这么难做到?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
相关资源
最近更新 更多