acts_as_list范围问题

时间:2011-08-02 21:14:30

标签: ruby-on-rails

我遇到的问题是在底部。

型号:

class Skill
  has_many :tags  
  acts_as_list :column => 'sequence'
end

class Tag
  belongs_to :skill 
  acts_as_list :column => 'sequence', :scope => :skill
end

查看:

<table id="skills">

  <% @skills.each do |s| %>
    <tr id="skill_<%= s.id %>">

      <td>
        <%= s.name %>
      </td>

      <td>
        <ul id="tags">
        <% s.tags.each do |t| %>
          <li id="tag_<%= t.id %>">
            <%= t.name %>
          </li>
        <% end %>
        </ul>
      </td>

    </tr>
  <% end %>

</table>

jQuery for drag and drop:

$( "#skills" ).sortable({          
  axis: 'y',
  dropOnEmpty: false,
  handle: '.handle',
  cursor: 'move',
  items: 'tr',
  opacity: 0.4,
  scroll: true,
  update: function(){
    $.ajax({
      type: 'post',
      data: $('#skills').sortable('serialize') + "&authenticity_token=" + "<%= form_authenticity_token %>",
      dataType: 'script',
      complete: function(request){
        $('#skills').effect('highlight');
      },
      url: '<%= url_for :action => 'sort', :controller => 'skills' %>'
    })
  }
});

$( "#tags" ).sortable({          
  axis: 'y',
  dropOnEmpty: false,
  handle: '.handle',
  cursor: 'move',
  items: 'li',
  opacity: 0.4,
  scroll: true,
  update: function(){
    $.ajax({
      type: 'post',
      data: $('#tags').sortable('serialize') + "&authenticity_token=" + "<%= form_authenticity_token %>",
      dataType: 'script',
      complete: function(request){
        $('#tags').effect('highlight');
      },
      url: '<%= url_for :action => 'sort', :controller => 'tags' %>'
    })
  }
});

标签控制器:

def sort
  @tags = Tag.all
  @tags.each do |tag|
    tag.sequence = params['tag'].index(tag.id.to_s) + 1
    tag.save
  end
  render :nothing => true
end

问题:

拖动标签后出现错误:

NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+):
  app/controllers/tags_controller.rb:12:in `block in sort'
  app/controllers/tags_controller.rb:11:in `each'
  app/controllers/tags_controller.rb:11:in `sort'

如果我加载属于特定技能的标签,我发现错误消失了:

def sort
  @tags = Skill.find(1).tags

问题 - 如何告诉控制器加载哪些标签(但不是所有标签)?


我找到的解决方案......

标签控制器:

def sort
  @tag = Tag.find(params[:tag]).first
  @skill = Skill.find_by_id(@tag.skill_id)
  @tags = @skill.tags

这是最好的方法吗?

1 个答案:

答案 0 :(得分:2)

  

评估nil时发生错误。+):

这意味着无论params['tag'].index(tag.id.to_s) + 1(来自控制器中的排序)应该做什么实际上导致nil + 1

如果您的解决方案按预期执行,那么我认为它没有问题。

作为提示,如果您在代码模型中执行@skill = Skill.find_by_id(@tag.skill_id),则@skill = @tag.skill可缩短为belongs_to :skill