2012-01-12 117 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