添加了gem并为#<class:0x00007f65df881b38>得到了此错误未定义方法`acts_as_votable'

时间:2019-04-25 11:23:42

标签: ruby-on-rails ruby

婴儿Ruby编码器在这里。

我按照此处的步骤操作:https://masteruby.github.io/weekly-rails/2014/08/05/how-to-add-voting-to-rails-app.html#.XMFebOhKg2w上传此act_as_votable gem,但是当我刷新网站以查看其是否正常工作时,出现以下错误:undefined method `acts_as_votable' for #<Class:0x00007f65df881b38> 该代码似乎不喜欢我在模型中使用act_as_votable的事实。

控制台中的错误也表明控制器中有问题。我是否也需要在其中定义一些内容?

谢谢,

安吉拉

我想在act_as_votable gem上使用模型,您可以看到我已经按照说明添加了它:

class Hairstyle < ApplicationRecord
     belongs_to :user, optional: true
     has_many :comments, dependent: :destroy
     validates :name, presence: true
     validates :description, presence: true
     validates :category, presence: true
     acts_as_votable 
     mount_uploader :photo, PhotoUploader
   end

我的发型控制器的末尾带有'upvote'方法:

class HairstylesController < ApplicationController
  def index
    if params[:category].present?    
      @hairstyles = Hairstyle.where(category: params[:category])
    elsif params[:search].present?
      @hairstyles = Hairstyle.where('name ILIKE ?', '%#{params[:search]}%')
    else
      @hairstyles = Hairstyle.all
    end
  end

  def show
    @hairstyle = Hairstyle.find(params[:id])
    @comment = Comment.new  
  end

  def new
    @hairstyle = Hairstyle.new
  end

  def create
    @hairstyle = Hairstyle.create(hairstyle_params)   
    @hairstyle.user = current_user
    if @hairstyle.save!
      redirect_to hairstyle_path(@hairstyle)
    else
      render 'new'
    end
  end

  def edit
    @hairstyle = Hairstyle.find(params[:id])
  end

  def update
    @hairstyle = Hairstyle.find(params[:id])
    @hairstyle.update(hairstyle_params)
    redirect_to hairstyles_path
  end

  def destroy
    @hairstyle = Hairstyle.find(params[:id])
    @hairstyle.destroy
    redirect_to hairstyles_path
  end

  def upvote
    @hairstyle = Hairstyle.find(params[:id])
    @hairstyle.upvote_by current_user
    redirect_to hairstyles_path
  end

  private

  def hairstyle_params
    params.require(:hairstyle).permit(:name, :description, :category, :location, :stylist, :photo, :video_url, :photo_cache)
  end
end

我的索引文件想在以下位置显示宝石:

  <% @hairstyles.each do |hairstyle| %>
    <%= link_to "upvote", like_hairstyle_path(hairstyle), method: :put%>
  <%end %>
</div>

如果需要,这是我的仓库:https://github.com/Angela-Inniss/hair-do

2 个答案:

答案 0 :(得分:1)

您似乎没有执行所有4个设置步骤:

  

将'acts_as_votable'添加到gemfile

然后从终端运行:

bundle install

rails generate acts_as_votable:migration

rake db:migrate

答案 1 :(得分:0)

我克隆并设置了您的仓库,我发现可能正在发生一些事情:

  • 我在此克隆中得到的原始错误是由于模型上的act_as_taggable引起的。您的模型应标注为acts_as_taggable(复数)
  • 当我最初进行测试时,我没有登录。这默默地失败了,这使得upvote似乎不起作用。除非用户已登录,否则您可能希望禁用这些功能。
  • 您的html / erb模板具有一些注释掉的代码等。这可能导致链接/ URL被吞噬并且不可点击。我通过删除除我正在测试的链接以外的所有样式和格式来解决此问题。我喜欢使用Haml来减少此类嵌套错误
  • 我没有遇到您的类错误,但是我建议运行spring stop并尝试再次启动服务器(我在所有Rails项目中均禁用spring)