多态关系:路线& Activeadmin

时间:2014-09-01 16:55:45

标签: ruby-on-rails routes activeadmin polymorphic-associations

我正在尝试找出多态关系,每当我尝试添加索引以显示所有带有activeadmin的+时,我的路由都会出现以下错误。

错误1:我为此尝试了许多不同的变体,有时我得到一个错误,有时没有错误但没有出现。

错误2:管理员中的NameError :: Places #index,未初始化的常量Place :: FavoritePlace,insert_tag renderer_for(:index)  --->对于此错误,我尝试添加remove_filter:favorites(以及不同的变体),但该解决方案不起作用。

我有一个模型,地方,我希望用户能够将地点添加到收藏列表中。我想要一个显示当前用户所有收藏的页面。用户现在可以喜欢/不喜欢一个地方。非常感谢任何帮助。谢谢!

place.rb

class Place < ActiveRecord::Base 
  #Favorites
  has_many :favorites
  has_many :favorite_places, through: :favorites, source: :favorited, source_type: 'Place'
end

favorite.rb

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :favorited, polymorphic: true
  belongs_to :place
end

favorite_places_controller.rb

class FavoritePlacesController < ApplicationController

   before_action :set_place,  except: [:index]

 def index
  @places = User.favorite_places
 end
 def create
    if Favorite.create(favorited: @place, user: current_user)
    redirect_to @place, notice: 'Place has been favorited'
  else
    redirect_to @place, alert: 'Something went wrong. *womp womp*'
  end
end

def destroy
  Favorite.where(favorited_id: @place.id, user_id: current_user.id).first.destroy
  redirect_to @place, notice: 'Place is no longer a favorite'
end

private

 def set_place
   @place = Place.find(params[:place_id] || params[:id])
 end
end

的routes.rb

#favorites
 resources :favorite_places

视图/ favorite_places / index.html.erb

<% @places.each do |place| %>     
  <div class="box panel panel-default">
      <div id="image-wrapper">
      <span itemprop="photo"><%= link_to image_tag(place.image.url(:medium)), place, class: "hover" %></span>

       <p class="image-text text-center"> <span itemprop="name">
             <%= place.name %>
         </span>
        <br>

        <span itemprop="servesCuisine"><%= ["beer", "chocolate" ,"cocktail", "coffee", "tea", "wine", "juice"] [place.kind] %>
        </span>
      </p>

    </div>

 </div>
<% end %>

admin / place.rb

ActiveAdmin.register Place do

   controller do
     def permitted_params
      params.permit place: [ :city_id, :description, :image_file_name, :image_content_type, :image_file_size, :name, :kind, :address, :latitude, :longitude, :website, :dress, :food, ":image_updated_at(1i)", ":image_updated_at(2i)", ":image_updated_at(3i)", ":image_updated_at(4i)", ":image_updated_at(5i)" ]
   end
   end
end

1 个答案:

答案 0 :(得分:0)

解决了这个问题。基本上,这两件事固定了它:

  1. 正在制作favorite_places多态以及收藏夹,不需要这样做,因为只有收藏夹应该是多态的。现在,

    class FavoritePlace < ActiveRecord::Base
       has_one :favorite, as: :favorited, dependent: :destroy
    end
    
  2. 未在 favorite_places_controller.rb 中指定用户应该说:

    def index
      @places = current_user.favorite_places.all
    end