【问题标题】:Ruby on Rails passing controller variables to viewRuby on Rails 将控制器变量传递给视图
【发布时间】:2014-01-26 23:29:50
【问题描述】:

您好,我很难理解为什么参数没有传递给视图。

控制器

class UsersController < ApplicationController
  include UsersHelper

  before_filter :set_user, :set_categories
  def show
    @test = get_test()
  end
end

帮手

module UsersHelper
   def get_test()
     puts "hello world"
   end
end

查看

test:  <%= @test %> 

正在显示什么test:

有人可以帮我解释为什么hello world 没有显示吗?谢谢!

--编辑-- 似乎我什至无法将任何变量消息传递给视图 我添加了...

控制器

@message = "How are you"

查看

<p><%= @message %></p>

并且How are you 没有显示。

【问题讨论】:

  • 您是否在相关操作中定义了@message

标签: ruby-on-rails ruby


【解决方案1】:

在您的get_test 函数中,您正在打印一个字符串而不是返回该字符串。返回一个字符串:

module UsersHelper
   def get_test()
     "hello world"
   end
end

【讨论】:

  • 感谢您确实解决了问题!你会碰巧知道如何解决我的编辑问题吗?
  • 你将如何返回一个变量,它只是@hello = "hello world"?还是只是 hello = "hello world",它会返回局部变量?
  • 对不起。我不太了解你。你的意思是给一个变量分配一个字符串?要从函数中返回一个字符串,请执行 return "hello world"。要让视图访问变量,您通常必须将其分配给实例变量,即@hello = "hello world"hello 没有 @ 将是局部变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 2010-12-21
  • 1970-01-01
相关资源
最近更新 更多