简体   繁体   中英

How to use POST with ruby on rails?

I created a blog application using rails. I'm trying use that as an API for a mobile app. I'm trying to write JSON to POST the content into the application.

#model/post.rb

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :category
end

#model/comment.rb

class Comment < ActiveRecord::Base

  belongs_to :post
end

#model/category.rb
   has_many :posts
#controllers/comments_controller

class CommentsController < ApplicationController
    before_action :set_comment, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!

# GET /comments/new
def new
  @comment = Comment.new
end

# GET /comments/1/edit
def edit
end

# POST /comments
# POST /comments.json
def create
  @comment = Comment.new(comment_params)

  respond_to do |format|
    if @comment.save
      format.html { redirect_to @comment, notice: 'comment was successfully created.' }
      format.json { render :show, status: :created, location: @comment }
    else
      format.html { render :new }
      format.json { render json: @comment.errors, status: :unprocessable_entity }
    end
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_comment
    @comment = Comment.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def comment_params
    params.require(:comment).permit(:rating, :comment, :post_id, :user_id)
  end
 end

What will be the JSON for the POST request for posting a blog post and a comment?

How should I pass association through JSON?

Here is the route for that action.

      POST       /comments(.:format)                        comments#create

If you want to be able to create a post and comment in the same request you will need to use accepts_nested_attributes_for .

class Post
  has_many :comments
  accepts_nested_attributes_for :comments
end

The params to create a post and a comment would look something like this:

{ 
  "post" : {
    "title": "Hello World",
    "comments_attributes": [
      {
        "rating": 3, 
        "comment": "Pretty mediocre if you ask me."
      }
    ]
  }
}

Rails does a pretty good job at abstracting out the difference between parameters sent as application/x-www-form-urlencoded, multipart or JSON. Dealing with JSON input is just like dealing with regular form input.

Then in your PostsController you would need to whitelist the nested attributes:

class PostsController < ApplicationController

  # POST /posts
  def create
    @post = Post.new(post_params)
    respond_to do |format|
    if @comment.save
      format.html { redirect_to @post, notice: 'comment was successfully created.' }
      format.json { render :show, status: :created, location: @post }
    else
      format.html { render :new }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end

  private
  def post_params
    params.require(:post).allow(:title, comments_attributes: [:rating, :comment])
  end
end

If you want your blog app to provide an API for external apps to use, you'll have to create an API layer within your application. This exposes endpoints that other apps can use to retrieve/post information to/from your site.

One of the first steps would be to scope out an api layer in your routes.rb :

YourBloggingApp::Application.routes.draw do
  namespace '/api', defaults: {format: 'json'} do
    scope '/v1' do
      scope '/blog_posts' do
        get '/' => 'api_blog_posts#index'
        post '/' => 'api_blog_posts#create'
          ...
      end
    end
  end
end

Then you can build the appropriate actions within your api controllers:

class Api::BlogPostsController < ApplicationController
  def index
    @blog_posts = BlogPost.all
  end

  def create
    @blog_post = BlogPost.create(title: params[:title], description: params[:description])
  end
  ...
end

And when a user from your mobile app fills out a form, the form can send a POST request to https://yourappdomain.com/api/v1/blog_posts/ , the blog_posts_controller#create action is triggered, which allows you to then pass in the given params sent through the request to create blog posts, comments, or whatever you set up in your project.

This is a very generic example, and there are a lot of specific details to cover on this topic, but this AirPair article provides a decent starting point for building a RESTful API.

{"comment":{"comment":"blah blah blah", "post_id":1}}

我必须在该POST请求中传递post_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM