0

对于嵌套表单,我将按照本教程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

我想创建一个新的帖子,因为我在board_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

通过这两种方法,我可以在我的视图中获得帖子的每个属性。在我的控制台中,如果我在创建板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 回答