【问题标题】:collection_select field nested forms rails 3.1collection_select 字段嵌套表单 rails 3.1
【发布时间】:2012-01-12 14:40:55
【问题描述】:

我有 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

我想在 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 %>

问题是在我的选择字段中出现了每个板我只想显示和选择属于_当前用户的图板。

注意我使用的是mongoid。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongoid nested-forms


    【解决方案1】:

    您的模型可以更简单。

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

    【讨论】:

    • 感谢 find_by_user_id 不适用于 mongoid :(。我正在使用 mongoid。谢谢!
    • 将此添加到您的帖子类中:scope :by_board, lambda |board_id| { where('board_id = ?', board_id) }
    • 谢谢,但我得到:语法错误!。我已经检查了这个:Board.where(:user_id == 'current_user.id') 但我又得到了每个板:S。如果板中的 :user_id 键与 current_user.id 相同,为什么要获取每个板
    • 问题已经解决了 :D 这句话是Board.where(:user_id =&gt; current_user.id)
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多