Rails,如何添加到方法html/js?

Rails, how add to method html/js?

比如我有很多类似的页面。只有一个区别:在每个页面上(它们有不同的控制器)它们有不同的变量,适用于这个 html.erb 文件。

例如视频posthtml.erb

<% for post in @posts_for_video>
  here some html
  and javascript
  and also ruby code injection
<% end %>

视频控制器:

@posts_for_video = Post.where(photo: true)

还有我的照片页面:

<% for post in @post_for_photos >
  same html as video
  same js as video
  and same ruby code as video
<% end %>

光控器:

@posts_for_photo = Post.where(video: photo)

所以我的问题是:有没有可能把 html+js+ruby_code 放到,例如 application_controller.rb?

或者是否可以将变量作为参数传递给_some.html.erb?

我想,我要找的是(在application_controller.rb):

def posts_for_all(post_variable)
  for post in post_variable
    html: post.theme
    js: post.animation
    ruby: some methods
  end
end

将整个代码变成部分代码?供参考:http://guides.rubyonrails.org/layouts_and_rendering.html

会是这样的:

# app/views/shared/_items.html.erb
<% items.each do |item| %>
  <!-- html stuff -->
  <!-- javascript stuff -->
  <%= # ruby stuff %>
<% end %>

然后你可以在另一个视图中渲染它:

# app/views/examples/show.html.erb
<%= render 'shared/items', items: @items %>

这是您要找的吗?

解决方案是使用 形式的部分

假设我们有一个页脚。我们不想在我们的网站上说网站是我们制作的。我们做什么?我们创建一个名称的部分形式

_footer.html.erb_ 表示这是局部视图,而不是像 show.html.erb 那样的完整视图)

里面我们可以写

<div class="container">
  <footer class="footer">
    <small>
      Copyright &copy;<a href = "https://ca.linkedin.com/in/muntasir-alam-878625114">Muntasir Alam 2016</a>
    </small>
    <nav>
      <nav>
        <ul>
          <li><%= link_to 'About', welcome_about_path %></li>
        </ul>
      </nav>
    </nav>
  </footer>
</div>

现在我们所要做的就是 render 这个视图出现在我们希望它出现的任何页面上。这不是比在每个页面上创建 html 好很多吗 ;D?

那application_controller.rb呢?

现在谈谈 application_controller.rb 的问题,我们用它做什么?

ApplicationController is practically the class which every other controller in you application is going to inherit from (although this is not mandatory in any mean).

为了参考,让我们在我自己的一个应用程序中查看我自己的 application_controller.rb 文件。

在我的class里面我有

helper_method :current_user, :logged_in?

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def logged_in?
    current_user
  end

  def require_user
    unless logged_in?
      flash[:danger] = "You must be logged in to perform that action!"
      redirect_to root_path
    end
  end

注意结构。我有一些代码将根据检查当前用户是否正在执行特定操作或用户是否实际登录来由其他一些控制器使用。

参考见 Partials and Layouts