【问题标题】:Rails, how add to method html/js?Rails,如何添加到方法 html/js?
【发布时间】:2016-09-02 12:23:30
【问题描述】:

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

例如视频帖子html.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

【问题讨论】:

  • 为什么要将它放在application_controller.rb 中?在我看来,将诸如处理登录检测的方法之类的东西放入其中是明智的,并在其中找到特定用户对应于特定事物的内容。
  • 即你应该保持干净,并且只保留其他 controller 将使用的功能。
  • @Muntasir Alam,关于 application.rb 只是作为示例。但我要说的是,不要在每个 html.erb 中重复代码(并且这个 html 中的唯一区别将是一个变量)。或者 mb 有可能将变量作为参数传递给 html.erb?
  • 让我直说。您想要一种始终在页面上显示某些内容的方法吗?如果是这样,我会发布解决方案

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

把整个代码变成一个部分?供参考: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 %>

这就是你要找的吗?

【讨论】:

  • 那个。试图解决它时打破我的头。谢谢!
【解决方案2】:

解决方案是使用 form partial

假设我们有一个页脚。我们不想放在我们的网站上,该网站是我们制作的。我们做什么?我们创建一个名称的部分表单

_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 更好吗?

application_controller.rb 呢?

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

ApplicationController 实际上是其他类 您应用程序中的控制器将继承自(尽管这 无论如何都不是强制性的)。

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

在我的班级里

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2012-10-04
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多