所以我的rails应用程序中有一个侧边栏。基本上,我有一个充满图像的网格。当有人点击网格中的图像时,我基本上希望显示视图显示在侧边栏中。我对如何做到这一点毫无头绪。
我已尝试将节目视图的html和erb复制并粘贴到我的_sidebar.html.erb
部分内容中。但我得到了可变错误。我的部分位于我的布局文件夹中。但如果需要我可以移动它。
这是一个应用程序的图像,可以更好地了解我正在谈论的内容。
答案 0 :(得分:2)
以下是如何操作:
1)在布局中加入sidebar
partial:
#app/views/layouts/application.html.erb
<%= render "shared/sidebar" %>
这会调用_sidebar.html.erb
中的/app/views/shared
部分:
2)填充“默认”侧边栏部分:
#app/views/shared/_sidebar.html.erb
...
这里需要注意的重要一点是, 从不 部分应该包含@instance
个变量。
部分有locals
,您可以使用以下命令传递:
<%= render "shared/sidebar", locals: { variable: "value" } %>
Partials 旨在在您的Web应用程序的任何部分上运行,并且因为@instance
变量存在于对象的单个“实例”中( IE @post
将无法在/users
中使用),您可以确保通过将局部变量传递给它们来确保局部变量。
这就是您将post#show
代码复制到sidebar
部分时收到错误的原因 - show
操作的实例变量不会出现在应用的其他部分
3)使用JS来提取图像对象
当有人点击网格中的图片时,我基本上希望展示视图显示在侧边栏中。
您需要更加具体 - 您真的希望“show”操作出现,还是您想要部分功能?
无论哪种方式,你最好使用JS&amp; ajax来拉取数据:
#app/controllers/images_controller.rb
class ImagesController < ApplicationController
layout Proc.new { |controller| !controller.request.xhr? }
end
#app/assets/javascripts/application.js
$(document).on("click", "img", function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data){
$(".sidebar .image").html(data);
});
});
这将采用呈现的images#show
操作(没有布局),并将其附加到侧边栏部分。这就是你要求的 - 如果需要,我可以改变它。
答案 1 :(得分:1)
让我们说你的模型被称为&#34; Image&#34;。
在你的&#34; images / show.html.erb&#34;:
# This is a handy shortcut that will call the 'images/_image' partial.
# Those two lines are exactly the same.
<%= render @image %>
<%= render "images/image", image: @image %>
在你的&#34; _sidebar.html.erb&#34;:
<div id="sidebar-img"></div>
在你的&#34; images / _image.html.erb&#34;:
# Code displaying your image, don't use any global variable.
# 'image' is the name of the local variable
在您的网格中:
# remote: true allows you to do an AJAX call
<%= link_to image, remote: true do %>
# Something like that, I don't know your code
<%= image_tag image.url %>
<% end %>
创建&#34; images / show.js.erb&#34;,点击遥控器:true&#39;链接它将调用此文件。
# set @image to Image.find(params[:id]) in your controller
$("#sidebar-img").html("<%= render @image %>");