【问题标题】:Maintaining the state of my tree based navigation rails维护基于树的导航栏的状态
【发布时间】:2012-03-27 12:54:12
【问题描述】:

我有一个基于树的导航,我想要跨控制器的各种操作。但是,当我通过单击 link_to 移动到另一个操作时,我的基于树的结构崩溃了。

如何维护状态?

如果需要,这里是代码:-

.three.columns
  %ul(class = "continent_name")
    - @destinations.group_by(&:continent).each do |continent, ds_per_continent|
      %li=link_to continent, "#"
      %ul(class = "country_name")
        - ds_per_continent.group_by(&:country).each do |country, ds_per_country|
          %li=link_to country, "#"
          %ul(class = "city_name")
            - ds_per_country.each do |destination|
              %li=link_to destination.name, destination_path(destination)

当我转到目标路径时,我希望国家名称可见,而不是全部折叠。如何做到这一点?

控制器代码

class DestinationsController < ApplicationController
    before_filter :find_destination, :except => [:index]
    before_filter :all_destinations

    def index   
    end

    def show
        @photos = @destination.destination_photos.all
        cookies['destination_id'] = params[:id]
    end

    def photos_videos
        @photos = @destination.destination_photos.all
    end

    def topic_blog
        @topics = Topic.all
    end

    private

    def find_destination
        @destination = Destination.find(params[:id])
    end

    def all_destinations
        @destinations = Destination.all
        cookies['destination_id'] = params[:id]
    end
end

JS 代码

$(document).ready(function(){
    $('.country_name').hide();
    $('.city_name').hide();
    $('li').click(function() {
        $(this).next('ul').toggle();
    });

    $('.city_name').click(function(){
    $('.destination').append();
    });
});

型号

class Destination < ActiveRecord::Base

    alias_attribute :city, :name
    validates :continent,   :presence   => true
    validates :country,     :presence   => true

end

jQuery

$('.country_name').hide();
    $('.city_name').hide();
    $('li').click(function() {
        $(this).next('ul').toggle();
    });

    $('.city_name').click(function(){
    $('.destination').append();
    });

【问题讨论】:

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


    【解决方案1】:

    在导航控制器中使用cookies 方法。要扩展的节点应该在cookie中注册,例如

    cookies['country_id'] = params[:country_id]
    

    然后在 JS 端,您可以使用 cookie plugin 中提供的 $.cookie 函数轻松提取节点,例如:

    $.cookie('country_id');
    

    【讨论】:

    • 是的,控制器代码中有一个错误 - 我已修复它,希望它现在可以工作。另外我不知道您的导航控制器代码看起来如何,所以我不确定应该在 cookie 中存储哪个变量。
    • 我正在用控制器代码更新我的问题,请看一下
    • 看不到控制器和视图的对应关系。此外,用于展开树节点的 jQuery/JS 代码也会有所帮助。你用什么插件吗?
    • 用JS代码和模型代码更新了代码,我没有使用任何插件。
    • 当我将鼠标悬停在树节点上时,它会将我带到在目标控制器中说“显示”的操作,它看起来像 localhost:3000/destination/id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2013-09-14
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    相关资源
    最近更新 更多