【问题标题】:Rails: passing an instance variable to different controller through a partialRails:通过部分将实例变量传递给不同的控制器
【发布时间】:2013-09-06 15:17:35
【问题描述】:

在类别视图中我有:

<ul>
  <% @category.subcategories.each do |subcategory| %>
    <li>
      <h6>
        <%if subcategory.has_topic_headings? %>
          <%= link_to subcategory.name, { controller: 'subcategories', 
                                          action: 'show_topic_headings',
                                          category_id: subcategory.category_id,
                                          id: subcategory.id 
                                        }, data: 'topic_heading_link', 
                                        remote: true %>
        <% else %>
          <%= link_to subcategory.name, subcategory %>
        <% end %>  
      </h6>
      <hr>
    </li>
  <% end %> 
</ul>            

在 application.js 中:

/* slides in the subcategory menu or the content */
$('.category-menu a').on(
'click',
function(e) {
  if ($(this).attr('data')) {
    /* make submenu visible */
    $('.stretched.nav.row > .slider').animate({left:'-62.5em'});
    e.preventDefault();
  }
  else {
    /* make content visible */
    $('.stretched.main.row > .slider').animate({left:'-62.5em'});
    e.preventDefault();
  }
}
);

在 subcategories_controller.rb 中

  def show_topic_headings
    respond_to :js
    @subcategory = Subcategory.find(params[:id])
  end

在 subcategories/show_topic_heading 我有:

$('.subcategory-menu').html( "<%= escape_javascript( render( partial: "layouts/topic_headings", locals: { subcategory: @subcategory} ) ) %>" );

单击活动链接, .subcategory-menu 应该填充正确的内容,并且包含的​​ div 应该滑入。但内容只有在它是静态的情况下才会出现(例如,如果我放置一个字符串而不是对@子类别)。请注意,我在其中插入子类别部分的视图是类别视图。

【问题讨论】:

    标签: ruby-on-rails ajax partials


    【解决方案1】:

    问题出在subcategories_controller:

    respond_to,而不是函数本身,生成部分。因此需要在调用response_to之前声明实例变量

    def show_topic_headings
      @subcategory = Subcategory.find(params[:id])
      respond_to :js
    end
    

    【讨论】:

      猜你喜欢
      • 2013-09-10
      • 2014-10-15
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多