加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在rails中创建动作

发布时间:2020-12-17 02:45:32 所属栏目:百科 来源:网络整理
导读:当我在rails中使用scaffold时,控制器会创建各种方法 new,create,show,index etc 但在这里我无法理解新行动的转变以创造行动 例如.当我点击新帖子它查找新动作时,现在它呈现_form,但是在提交时如何将数据输入到该特定表中,控制器的创建动作在哪里调用?如何?
当我在rails中使用scaffold时,控制器会创建各种方法

new,create,show,index etc

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

例如.当我点击新帖子它查找新动作时,现在它呈现_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

解决方法

默认情况下脚手架形式( 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

如果您想在新表格脚手架上自定义操作,则应添加: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,:status => :unprocessable_entity }
    end
  end
end

#route
match '/posts/YourActionName`,'controllers#YourActionName',:via => :post

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读