4

レールで足場を使用すると、コントローラーは次のようなさまざまなメソッドを作成します

新規、作成、表示、索引など

しかし、ここではアクションを作成するための新しいアクションの遷移を理解できません

例えば。新しい投稿をクリックすると、新しいアクションが検索され、_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
4

3 に答える 3

1

HTTP動詞とルートがすべてです。

フォームは/postsルートに対して POST リクエストを行います。を使用してルートを一覧表示すると、その特定のルートへのすべての POST 要求が、または略して のアクションにrake routes送信されていることがわかります。createPostsControllerposts#create

于 2013-06-16T03:10:34.413 に答える
1

ブラウザを にポイントすると/posts/new、アクションがレンダリングされ、入力するフォームが表示されます (およびnewで定義されています。フォームの [送信] ボタンをクリックすると、データがアクションにポストされ、実際に にレコードが作成されます)。データベース。app/views/posts/new.html.erbapp/views/posts/_form.html.erbcreate

PostsController コードを見ると、おそらく次の行は必要ないでしょう。

@post.save

これはnew、ユーザーがフォームに入力するかどうかに関係なく、空白のレコードがデータベースに保存されるためです。そして、あなたはおそらく移動したいと思うでしょう

@post.user_id = current_user.id

createこれは実際に投稿をデータベースに保存する場所であるためです。

于 2013-06-16T03:10:46.540 に答える