2012-01-12 110 views
0

我有3個模型中的第一user.rb:collection_select字段嵌套形式軌3.1

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 

第三種模式其職位。 rb

class Post 
belongs_to :user 
belongs_to :board 
end 

我想要在我從posts_controllers行動新創建一個新的職位有母基板我:

@post = Post.new 
respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @post } 
end 

我創建了一個新的董事會:

def create 
    @board = current_user.boards.new(params[:board]) 
    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 

在部分_form.thml.erb我有這個:

<%= form_for(@post, :html => {:multipart => true}) do |f| %> 
<%= f.label :content %><br /> 
<%= f.text_area :content %> 
<%= f.collection_select :board_id, Board.all, :id, :name%> 
<%= f.submit %> 
<% end %> 

問題是,在我的s選舉字段出現在每個主板我只想顯示並選擇屬於current_user的板。

注意我正在使用mongoid。

回答

0

您的模型可以更簡單。

class User 
has_many :boards, dependent: :destroy 
accepts_nested_attributes_for :boards 
end 

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

class Post 
belongs_to :board 
end 

<%= form_for(@post, :html => {:multipart => true}) do |f| %> 
<%= f.label :content %><br /> 
<%= f.text_area :content %> 
<%= f.collection_select :board_id, Board.find_by_user_id(current_user.id), :id, :name%> 
<%= f.submit %> 
<% end %> 
+0

感謝find_by_user_id使用mongoid不爲mongoid :(工作進出口感謝 – hyperrjas 2012-01-12 15:00:03

+0

添加到您的職位等級:範圍:!by_board,拉姆達| board_id | {其中,( 'board_id =?',board_id)} – 2012-01-12 15:29:07

+0

謝謝,但我得到:**語法錯誤!**。我檢查這個:** Board.where(:user_id =='current_user.id')**但我再次獲得每個板:S。爲什麼得到**每個主板**如果:user_id鍵盤與其current_user.id相同 – hyperrjas 2012-01-12 15:38:03