当我在 rails 中使用脚手架时, Controller 会创建各种方法,例如
new,create,show,index etc
但在这里我无法理解新 Action 到创建 Action 的过渡
例如。当我点击新的 Post 时它会查找新的 Action ,现在它呈现 _form,但是当提交时数据如何输入到那个特定的表, Controller 的创建 Action 在哪里调用以及如何调用?
我的 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
最佳答案
默认情况下,表单上的脚手架 ( read here )
When the user clicks the Create Post button on this form, the browser will send information back to the create action of the controller (Rails knows to call the create action because the form is sent with an HTTP POST request; that’s one of the conventions that were mentioned earlier):
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
如果你想在新的表单脚手架上自定义一个 Action ,你应该在你的表单上添加 :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
关于ruby-on-rails - 在 Rails 中创建 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17129801/