0

このhttp://railscasts.com/episodes/382-taggingに基づいて、自分のサイトにタグ付けを実装しました

家のリソースにタグを追加したいので、次のようなURLを取得します...

/ houses / tag1 / houses / tag2 ect

私のルートファイル:

localized(['en', 'nl', 'de']) do
  scope "/:locale" do
    resources :houses do
      collection do
        get ':tag', to: 'houses#index', as: :tag
      end
    #...
    end
  end
end

ハウスコントローラー

if params[:tag]
  @houses = House.tagged_with(params[:tag])
  @tag = Tag.find_by_name(params[:tag])
else
  @houses = House.find.all
end

住宅モデル(一部)

def self.tagged_with(name)
       Tag.find_by_name!(name).houses
     end

      def self.tag_counts
        Tag.select("tags.*, count(taggings.tag_id) as count").
          joins(:taggings).group("taggings.tag_id")
      end

      def tag_list
        tags.map(&:name).join(", ")
      end

      def tag_list=(names)
        self.tags = names.split(",").map do |n|
          Tag.where(name: n.strip).first_or_create!
        end
      end

これは、家のリソースのタグに対しては正常に機能します。しかし、例の家/家名1で家ID(showメソッド)に行くと、エラーメッセージが表示されます

undefined method `houses' for nil:NilClass
house.rb:41:in `tagged_with'

私は何が間違っているのですか?

Ciao..remco

4

1 に答える 1

0

家とタグのルートは崩壊しています。タグにアクセスする方法を決定する必要があります。私はどちらかを提案します:

オプション1

タグは別のリソースである可能性があります。

resources :houses
resources :tags

オプション2

タグは、へのフィルターのようなものである可能性がありますhouses#index。この場合、ルートにタグを定義する必要はありません。次のようにするだけです。

resources :houses

次に、この種のルートを使用して、タグで家をフィルタリングします。

/houses/?tag=tag1
于 2012-12-05T22:09:59.240 に答える