是否可以将注释控制器用于两个不同的东西?

时间:2011-08-15 12:33:12

标签: ruby-on-rails ruby ruby-on-rails-3

class CommentsController < ApplicationController
  def create
    @contact = Contact.find(params[:contact_id])
    @comment = @contact.comments.create(params[:comment])
    respond_to do |format|
      format.html { redirect_to contact_path(@contact) }
      format.js
    end
  end
  def destroy
    @contact = Contact.find(params[:contact_id])
    @comment = @contact.comments.find(params[:id])
    @comment.destroy
    respond_to do |format|
       format.html { redirect_to contact_path(@contact) }
       format.js
     end
  end
end

是否可以创建和销毁公司模型的评论?如何检查用户是否在某个页面上?因为那时我只能有一个if语句。

更改后的CommentsController

class CommentsController < ApplicationController
  def create
    @object = find_object
    @comment = @object.comments.create(params[:comment])
      respond_to do |format|
        format.html { redirect_to [@object] }
        format.js
      end
  end

  def destroy
    @object = find_object
    @comment = object.comments.find(params[:id])
    @comment.destroy
    respond_to do |format|
       format.html { redirect_to [@object] }
       format.js
     end
  end

  private
  def object
    @object = if params[:contact_id]
      Contact.find(params[:contact_id]
    elsif params[:company_id]
      Company.find(params[:company_id])
    end
  end
end

1 个答案:

答案 0 :(得分:4)

你可以用路由

来做
# routes.rb
resources :contacts do
  resources :comments
end
resources :company do
  resources :comments
end

因此,在控制器中,如果有任何公司或联系人,您可以处理:

def destroy
  @object = find_object
  @comment = @object.comments.find(params[:id])
  @comment.destroy
  redirect_to [@object]
end

private
def find_object
  @object = if params[:contact_id]
    Contact.find(params[:contact_id])
  elsif params[:company_id]
    Company.find(params[:company_id])
  end
end

但这里最好的解决方案是在这里使用POLYMORPHISM。退房:

  

http://railscasts.com/episodes/154-polymorphic-association