需要使用Rails和mongoid在MongoDB中保存关系

时间:2013-03-03 18:28:48

标签: ruby-on-rails ruby mongodb mongoid

我需要使用Rails collection_select在我的用户文档中保存group_id 代码列在下面

模特用户:

class User
 include Mongoid::Document
 include Mongoid::Timestamps
 include Amistad::FriendModel

 field :name, :type => String
 field :email,              :type => String, :default => ""
 field :encrypted_password, :type => String, :default => ""

#relations
  belongs_to :school
  belongs_to :group

模型组

 class Group
   include Mongoid::Document
   attr_accessible :name, :degree
   field :name, type: String
   field :degree, type: String
   has_many :users

并生成表格:

<%= form_for(@user) do |f| %>
  <%= f.email_field :email %></div>
  <%= f.password_field :password %>
  <%= f.collection_select :group_id,  Group.all, :id, :name %>
  <%= f.submit "Sign up" %>
<%end%>

这会保存用户文档而不保存collection_select中的group_id提及,任何想法

2 个答案:

答案 0 :(得分:0)

在创建新用户或Group.user.create时是否使用User.new。后者应该工作。

答案 1 :(得分:0)

这不是更好的方法,但它有效

def create
@user = User.new(params[:user])
@user.school_id = current_user.school_id
@user.group_id = params[:user][:group_id]
respond_to do |format|
  if @user.save
    format.html { redirect_to @user, notice: 'Subject was successfully created.' }
    format.json { render json: @user, status: :created, location: @subject }
  else
    format.html { render  "new" }
    format.json { render json: @subject.errors, status: :unprocessable_entity }
  end
end