kushtrimh
kushtrimh

Reputation: 916

Create a blog that only I can post - Rails?

This question may be stupid but I want to create a blog with rails so only I as an Admin can post Articles and others can comment to articles but they don't need to create an account to comment.

So basically how to make it so only I have an User/Account and with that user I can post Articles when I Log In. I thought of matching the login action to a "secret" route for example like /blablalogin.

Upvotes: 0

Views: 476

Answers (2)

Leantraxxx
Leantraxxx

Reputation: 4606

I would do...

  • Create a Post model running rails g model post title:string body:text

    class Post < ActiveRecord::Base
      belongs_to :admin_user
      has_many :comments, dependent: :destroy
      accepts_nested_attributes_for :comments, reject_if: :all_blank, allow_destroy: true
    end
    
  • Install ActiveAdmin for admin site. Easily you can create a blog posts CRUD using Active Admin.

  • Create User model. Using devise you can solve the "login part" for users.

    You don't need devise if it`s not necessary to be logged in to write comments

  • Create Comment model. rails g model post title:string body:text user:references post:references

    class Comment < ActiveRecord::Base
      belongs_to :user # you won't need this relation if users don't need to be logged in.
      belongs_to :post
    end
    
  • Create a PostsController with index and show actions only.

  • Create a CommentsController with create action only. Don't forget permitted params:

    def permitted_params
      params.require(:post).permit(comments_attributes: [:title, :body])
    end
    
  • The routes:

    resources :posts, only: [:index, :show] do
      resources :comments, only: [:create]  
    end
    

    You will have:

    • GET /posts the view containing posts list
    • GET /posts/:id view for specific post. Here you need a form to enter comments pointing to POST /posts/:id/comments
    • POST /posts/:id/comments endpoint to save comments for a single post.
  • You should know about nested attributes it you want to create comments for a single post in a rails way.

Upvotes: 0

Md Sirajus Salayhin
Md Sirajus Salayhin

Reputation: 5144

You can create a separate controller for blog and also create a user access level. Now you can add your user to a special role who can manage Blog controller.

To create access level you can use devise with cancan.

Devise

Cancan

Update:

Also you can add this with active admin as Gaurav Gupta said.

Upvotes: 1

Related Questions