我想通过在我的控制器中的创建操作中使用 post 方法从客户端获取数据到 ruby on rails。但我不知道如何在 def create 操作中从客户端获取数据。如何创建用于获取数据的 api从客户端。
后控制器.rb
class PostsController < ApplicationController
respond_to :json, :xml
before_filter :load
def load
if signed_in?
@my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
@my_post = current_user.posts.new
end
@posts = Post.paginate(page: params[:page],:per_page => 10)
@post = Post.new
end
def index
@posts = Post.all
respond_with(@posts) do |format|
format.json { render json: @post_names = {:post => @posts.as_json(:only=> :content)} }
end
end
def show
if signed_in?
@post = Post.find(params[:id])
@my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
current_user.vote_for(@post)
else
@post = Post.find(params[:id])
Guest.find(1).vote_for(@post)
end
@posts = Post.paginate(page: params[:page],:per_page => 10)
@guest = Guest.new
@user = User.new
@users = User.paginate(page: params[:page],:per_page => 10)
end
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
@posts = Post.paginate(page: params[:page],:per_page => 10)
format.json { render json: @post, status: :created }
else
@posts = Post.paginate(page: params[:page],:per_page => 10)
format.json { render json: @post.errors, status: :unprocessable_entity }
end
@guest = Guest.new
@users = User.paginate(page: params[:page],:per_page => 10)
end
end
def my_prayer_create
@my_post = current_user.posts.new(params[:post])
@post = Post.new(params[:post])
@guest = Guest.new
@user = User.new
@users = User.paginate(page: params[:page],:per_page => 10)
if @my_post.save
flash[:notice] = "Prayer Successfully created."
@my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
else
flash[:notice] = "Error"
@my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
end
end
def edit
if signed_in?
@my_post = current_user.posts.find(params[:id])
else
@post = Post.find(params[:id])
end
end
def update
if signed_in?
@my_post = current_user.posts.find(params[:id])
if @my_post.update_attributes(params[:post])
flash[:notice] = "Prayer Successfully updated."
@my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
end
else
@post = Post.find(params[:id])
end
end
def destroy
if signed_in?
@my_post = current_user.posts.find(params[:id])
@users = User.paginate(page: params[:page],:per_page => 10)
@guest = Guest.new
@my_post.destroy
flash[:notice] = "Prayer Successfully destroyed."
@my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
end
end
对于我的控制器,我如何从客户端获取数据。从这里我只需要在客户端写入 url 也像这样"http://localhost:3000/posts"