使用具有嵌套关联的多态路径创建新项目

时间:2013-03-15 20:18:24

标签: ruby-on-rails-3 cancan nested-routes

我希望能够分别为两个模型编写评论(使用具有嵌套关联的多态路径)。目前,我有一个问题,如果我想写一个城市的评论,那么记录是为国家而不是城市创建的


http://localhost:3000/countries/1/reviews/new

为该国家创建了良好的概述,

=> #<Review id: 1, content: "", reviewable_id: 1, reviewable_type: "Country", created_at: "2013-03-15 18:57:15", updated_at: "2013-03-15 18:57:15">

但:

http://localhost:3000/countries/1/cities/1/reviews/new

再次为国家而不是为城市创建评论

=> [#<Review id: 2, content: "second", reviewable_id: 1, reviewable_type: "Country", created_at: "2013-03-15 19:00:34", updated_at: "2013-03-15 19:00:34">]

请告诉我,如何使用具有嵌套关联的多态路径为城市创建评论?


my routes.rb:

  resources :countries do
    resources :reviews
    resources :cities do
      resources :reviews
    end
  end

审核控制器

class ReviewsController < ApplicationController
  load_resource :country
  load_resource :city
  load_and_authorize_resource :review, :through => [:country, :city]

  def new; end

  def create
    respond_to do |format|
      if @review.save
        format.html { redirect_to @review, notice: 'Review was successfully created.' }
        format.json { render json: @review, status: :created, location: @review }
      else
        format.html { render action: "new" }
        format.json { render json: @review.errors, status: :unprocessable_entity }
      end
    end
  end

  ....
end

评论指数

%h1 Listing reviews
= link_to 'New Review', new_polymorphic_path([@country, @city, :review]) if can? :new, Review

和表格

= form_for(@review, url: polymorphic_path([@country, @city, @review])) do |f|

  .field
    = f.label :content
    %br/
    = f.text_area :content
  .actions
    = f.submit

提前致谢!

0 个答案:

没有答案