Ruby on rails 与rails中的多个控制器相关的控制器

Ruby on rails 与rails中的多个控制器相关的控制器,ruby-on-rails,controller,Ruby On Rails,Controller,我认为这是一个艰难的过程。我有一个comments控制器,我想用于所有其他控制器:例如书籍、标题等 问题是,注释中的创建操作是: def create @book = Book.find(params[:book_id]) @comment = @book.comments.create!(params[:comment]) respond_to do |format| format.html {redirect_to @book} format.js end

我认为这是一个艰难的过程。我有一个comments控制器,我想用于所有其他控制器:例如书籍、标题等

问题是,注释中的创建操作是:

  def create
  @book = Book.find(params[:book_id])
  @comment = @book.comments.create!(params[:comment])
  respond_to do |format|
    format.html {redirect_to @book}
    format.js
  end
结束


那么,如果我清楚地使用了图书属性,那么如何使用“动作和评论”控制器来制作标题呢?

这也是我一直在思考的问题。首先,您必须使create方法独立于父级

然后您将有两个选项:

  • 对于评论可能附加到的每件事都有一个belonsg_,并有选择地填写其中一个
  • 这些书/标题等是否属于评论

  • 我自己对Rails相当陌生,所以我不知道这是做事情的“正确方式”,也许其他人有更好的解决方案。

    好吧,如果不具体说明每个控制器的属性,通常无法做到这一点

    如果您想为应用程序中的一组模型创建一个通用注释模型,则需要传递您要注释的模型类型(而不是模型本身),然后创建一个开关,该开关将根据您传递的内容提供不同的行为

    def create
      if params[:type]="book"
        @book = Book.find(params[:book_id])
        @comment = @book.comments.create!(params[:comment])
        respond_to do |format|
          format.html {redirect_to @book}
          format.js
      elsif params[:type]="title"
        @title = Title.find(params[:title_id])
        @comment = @title.comments.create!(params[:comment])
        respond_to do |format|
          format.html {redirect_to @title}
          format.js
      end
    end
    

    我想这可能就是你要找的。在资源控制器上。

    我假设您在注释上有多态关联设置,因此它可以属于许多不同类型的模型?看一看,它向您展示了如何设置控制器动作。下面是关键的代码

    # comments_controller
    def create
      @commentable = find_commentable
      @comment = @commentable.comments.build(params[:comment])
      if @comment.save
        flash[:notice] = "Successfully created comment."
        redirect_to :id => nil
      else
        render :action => 'new'
      end
    end
    
    private
    
    def find_commentable
      params.each do |name, value|
        if name =~ /(.+)_id$/
          return $1.classify.constantize.find(value)
        end
      end
      nil
    end
    
    # routes.rb
    map.resources :books, :has_many => :comments
    map.resources :titles, :has_many => :comments
    map.resources :articles, :has_many => :comments