Controller associated with multiple controllers in rails

It is difficult, I think. I have a comment controller that I would like to use for all my other controllers: for example, books, headings, etc.

The problem is creating the action in the 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

end

so how can I use an action and comment controller for headings if it explicitly uses book attributes?

+3
source share
4 answers

, , ? Railscasts, , . .

# 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
+5

, . create , .

:

  • belonsg_to , , .
  • //etc

Rails, , " " , , - .

0

, , .

If you want to create a common comment model for a bunch of models in your application, you need to pass in the type of model you are commenting on (but not the model itself), and then create a switch that will provide different behavior based on what you are going through.

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
0
source

I think the resource controller is probably exactly what you are looking for. Here is another link to the resource controller.

0
source

Source: https://habr.com/ru/post/1715219/


All Articles