Search code examples
ruby-on-railsruby-on-rails-4single-table-inheritancesti

Rails/STI - common model path


I'm trying to learn how STI works and I have my Content model set up with Post and Article inheriting from it.

I also have a Comment model. In the comments controller, I have this:

def find_content
  @content = Content.find(params[:content_id])
end

Obviously, it isn't working since the params show either post_id or article_id. How do I tell the comments controller to pull in the relevant content_id based on the params?


Solution

  • A quick fix could be:

    @content = Content.find(params[:post_id] || params[:article_id])
    

    In your parameters should be either an article_id or a post_id. So you can try to catch both parameters and combine them with a logical or operator (||). So you get an article_id or a post_id which you can use with Content.find.

    params
    # => {:article_id=>1, :other_parameter=>"value"}
    
    params[:post_id] || params[:article_id]
    # => 1
    

    If there is neither of the parameters you get nil and Content.find fails with a ActiveRecord::RecordNotFound exception. That's ok, I think. Later you will rescue this error in your controller to show a 404 page .