开发者

Is it possible to use the comments controller for two different things?

开发者 https://www.devze.com 2023-03-27 23:28 出处:网络
class CommentsController < ApplicationController def create @contact = Contact.find(params[:contact_id])
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

Is it possible to also create and destroy comments for the company model? How do you check whether a user is on a certain page? Because then I can just have an if statement.

The changed 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|
开发者_StackOverflow社区       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


you can do it with routing

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

So in controller you can handle if there any company or contact around:

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

But best solution here is to use POLYMORPHISM here. Check out:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消