Ruby on rails Rails 4:控制器和模型中有什么?

Ruby on rails Rails 4:控制器和模型中有什么?,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 4,我一直在阅读和观看一些关于学习Rails 4的视频。所有教程都有自己的代码,因此在我看来,很容易理解。我似乎什么都学不到,也记不住什么东西,所以我决定使用自己的代码,看看是否可以遵循这些代码,而不是使用他们的代码 到目前为止,我了解控制器与视图相对应: # In my controller def index @x = "I love Ruby" end 在我的视图中(index.html.erb) 仍在控制器的类中: def languages_i_hate languages = %w

我一直在阅读和观看一些关于学习Rails 4的视频。所有教程都有自己的代码,因此在我看来,很容易理解。我似乎什么都学不到,也记不住什么东西,所以我决定使用自己的代码,看看是否可以遵循这些代码,而不是使用他们的代码

到目前为止,我了解控制器与视图相对应:

# In my controller
def index
 @x = "I love Ruby"
end
在我的视图中(index.html.erb)

仍在控制器的类中:

def languages_i_hate
 languages = %w[
                 Perl
                 PHP
                 C#
                 C++ ]
end
在my index.html.erb中:

<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!
<%= "These are the languages I hate to bits: #{@languages_i_hate}" %>
<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!%>

您在这里尝试的是访问视图中的控制器方法。执行此操作时,控制器方法将被访问,就像它是一个助手方法一样。通常情况下,控制器方法不能以这种方式使用,但您可以告诉控制器使它们作为帮助器可用

顺便说一句,如果控制器中的方法不是操作,即与路由/url不对应,则应按照惯例将它们放在控制器底部的
受保护的
部分。这向rails和读者清楚地表明,它们不是动作

def index
 @x = "I love Ruby"
 languages_i_hate
end


def languages_i_hate
 @languages = %w[Perl PHP C#  C++ ]
end
index.html.erb:

<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!
<%= "These are the languages I hate to bits: #{@languages_i_hate}" %>
<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!%>

根据rails惯例,您必须使用助手。另一种方法是在渲染模板时使用局部变量

def index
 @x = "I love Ruby"
 render :template => "index.html.erb", :locals =>{:languages_i_hate => languages_i_hate}
end

def languages_i_hate
 languages = %w[
             Perl
             PHP
             C#
             C++ ]
 end
在my index.html.erb中:

<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!
<%= "These are the languages I hate to bits: #{@languages_i_hate}" %>
<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!%>


没有。我知道我可以使用变量。我需要知道为什么我不能调用其他方法。要调用任何方法,您需要任何对象。只要看看你的代码,你就会知道你犯了什么错误。