Search code examples
ruby-on-railsrubyruby-on-rails-pluginsrails-enginesmonologue

How to use Monologue gem in native app (getting posts from Monologue into root app)


I'm using the Monologue gem (rails engine for blogging) and mounting it in my app at /blog, I want to get the posts with a certain tag and display those posts on the home page of my app ('/'). From rails c I can get a tag OR a post by doing Monologue::Tag or Monologue::Post but when I try to do Monologue::Tag.posts.published (like how he has the app getting the posts for a specific tag in source) I get "undefined method". I know it's because it's an engine, I'm just not familiar enough with engines to know what the proper syntax for this is? Any help is much appreciated!


Solution

  • You are trying to get the posts for a specific tag right? Then, this is not what you want:

    Monologue::Tag.posts.published
    

    You are not specifying any tag here, you are calling the method posts on Monologue::Tag, but that is not a specific tag instance, it is the Monologue::Tag class.

    Once you have a specific tag, you will be able to call posts.published on it, or as I see in the source, you can even call posts_with_tag

    I guess that in order to try this, you could just get the first tag and then call the method:

    Monologue::Tag.first.posts.published
    

    Edit:

    As I told you in the comment, your problem was that you were trying to call the method posts to an object that was not of the class Monologue::Tag (your model), but of the class ActiveRecord::Relation (a collection of Monologue::Tag objects).. Doing the first works, because is returning the first instance that was found by the where.

    Another approach, if you know that you just want to fetch one instance, is to call find instead of where. Like this:

    Monologue::Tag.find_by(name: "Goals")

    This will return an instance of Monologue::Tag.