Search code examples
ruby-on-railsruby-on-rails-3nested-formsuserid

get user_id Devise in nested form rails 3.1


I'm follow this tutorial http://railscasts.com/episodes/196-nested-model-form-part-1 for nested form.

I have 3 model the first 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

The second model its board.rb

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

The third model its post.rb

class Post
belongs_to :user
belongs_to :board
end

I want create a new post since a board form and I have in 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

With this 2 methods I get every attributes of posts in my views. in my console if I put after create a board Post.first I get:

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"> 

But If you take a look I get user_id: nil.

In normal model I get user id for example in create action of controller I put @post.user = current_user.id or @post.user = current_user

How Can I get the user_id in nested model post through from nested forms?


Solution

  • 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