在rails中创建动作

Aka*_*nde 4 ruby ruby-on-rails ruby-on-rails-3

当我在rails中使用scaffold时,控制器会创建各种方法

新的,创造,展示,索引等

但在这里我无法理解新行动的转变以创造行动

例如.当我点击新帖子它查找新动作时,现在它呈现_form,但是在提交时如何将数据输入到该特定表中,控制器的创建动作在哪里调用?如何?

我的posts_controller

def new
@post = Post.new
@post.user_id = current_user.id
@post.save
respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @post }
end
end

# GET /posts/1/edit
def edit
@post = Post.find(params[:id])
authorize! :manage, @post
end

# POST /posts
# POST /posts.json
def create
@post = Post.new(params[:post])

respond_to do |format|
  if @post.save
    format.html { redirect_to @post, notice: 'Post was successfully created.' }
    format.json { render json: @post, status: :created, location: @post }
  else
    format.html { render action: "new" }
    format.json { render json: @post.errors, status: :unprocessable_entity }
  end
end
end
Run Code Online (Sandbox Code Playgroud)

rai*_*_id 5

默认情况下脚手架形式(在这里阅读)

当用户单击此表单上的"创建发布"按钮时,浏览器将信息发送回控制器的创建操作(Rails知道调用创建操作,因为表单是通过HTTP POST请求发送的;这是约定之一前面提到过):

def create
  @post = Post.new(params[:post])

  respond_to do |format|
    if @post.save
      format.html  { redirect_to(@post,
                    :notice => 'Post was successfully created.') }
      format.json  { render :json => @post,
                    :status => :created, :location => @post }
    else
      format.html  { render :action => "new" }
      format.json  { render :json => @post.errors,
                    :status => :unprocessable_entity }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

如果要在新表单脚手架上自定义操作,则应:url => {:action => "YourActionName"}在表单上添加.

示例:

#form
form_for @post, :url => {:action => "YourActionName"}

#controller
def YourActionName
  @post = Post.new(params[:post])

  respond_to do |format|
    if @post.save
      format.html  { redirect_to(@post,
                    :notice => 'Post was successfully created.') }
      format.json  { render :json => @post,
                    :status => :created, :location => @post }
    else
      format.html  { render :action => "new" }
      format.json  { render :json => @post.errors,
                    :status => :unprocessable_entity }
    end
  end
end

#route
match '/posts/YourActionName`, 'controllers#YourActionName', :via => :post
Run Code Online (Sandbox Code Playgroud)