我正在按照本教程http://railscasts.com/episodes/196-nested-model-form-part-1了解嵌套表单。
我有3个模型第一个 user.rb :
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
第二个模型是 board.rb
class Board
has_many :posts, :dependent => :destroy , :autosave => true
accepts_nested_attributes_for :posts
belongs_to :user
end
第三个模型是 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?
答案 0 :(得分: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
答案 1 :(得分: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