0

ネストされたフォームについては、このチュートリアルhttp://railscasts.com/episodes/196-nested-model-form-part-1に従っています。

最初のuser.rbの 3 つのモデルがあります。

class User
 has_many :boards, dependent: :destroy
 has_many :posts, dependent: :destroy, :autosave => true
 accepts_nested_attributes_for :boards
 accepts_nested_attributes_for :posts

end

2番目のモデルは board.rb

class Board
has_many :posts, :dependent => :destroy , :autosave => true
accepts_nested_attributes_for :posts
belongs_to :user
end

3 番目のモデルのpost.rb

class Post
belongs_to :user
belongs_to :board
end

ボードフォームから新しい投稿を作成したいのですが、 boards_controller.rbにあります

def new
  @board = Board.new
  @board.posts.build
 respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @board }
 end
end

def create
 @board = current_user.boards.new(params[:board])
 @board.user = current_user
respond_to do |format|
  if @board.save
    format.html { redirect_to @board, notice: 'Board was successfully created.' }
    format.json { render json: @board, status: :created, location: @board }
  else
    format.html { render action: "new" }
    format.json { render json: @board.errors, status: :unprocessable_entity }
  end
end
end

この 2 つのメソッドを使用して、ビュー内の投稿のすべての属性を取得します。ボードを作成した後にコンソールにPost.firstを配置すると、次のようになります。

1.9.2-p290 :007 > Post.first
=> #<Post _id: 4f0b0b211d41c80d08002afe, _type: nil, created_at: 2012-01-09 15:43:29 UTC, user_id: nil, board_id: BSON::ObjectId('4f0b0b1b1d41c80d08002afd'), content: "hello post 2"> 

しかし、見てみると、user_id: nilが表示されます。

通常のモデルでは、たとえばコントローラーの作成アクションでユーザーIDを取得します@post.user = current_user.id または @post.user = current_userを配置します

ネストされたフォームからネストされたモデルの投稿で user_id を取得するにはどうすればよいですか?

4

2 に答える 2

2
def create
 @board = current_user.boards.new(params[:board])
 #@board.user = current_user - you don't need this line, since you create new board record using current_user object
 # assign current_user id to the each post.user_id
@board.posts.each {|post| post.user_id = current_user}

respond_to do |format|
   if @board.save
     format.html { redirect_to @board, notice: 'Board was successfully created.' }
     format.json { render json: @board, status: :created, location: @board }
   else
    format.html { render action: "new" }
    format.json { render json: @board.errors, status: :unprocessable_entity }
   end
 end
end
于 2012-01-09T19:21:22.493 に答える
0

user_idプロパティを設定するだけでよいはずです。

current_userコードでは、オブジェクトを関連付けに割り当てています。

これは機能するはずです:

def create
 @board = current_user.boards.new(params[:board])
 @board.user_id = current_user.id
respond_to do |format|
  if @board.save
    format.html { redirect_to @board, notice: 'Board was successfully created.' }
    format.json { render json: @board, status: :created, location: @board }
  else
    format.html { render action: "new" }
    format.json { render json: @board.errors, status: :unprocessable_entity }
  end
end
end
于 2012-01-09T17:08:02.603 に答える