简体   繁体   English

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

[英]Need to Save Relationship in MongoDB with Rails and mongoid

I need to save group_id in my user document using Rails collection_select Code Listed Below 我需要使用下面列出的Rails collection_select代码将group_id保存在我的用户文档中

Model User: 模型用户:

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

Model Group 模型组

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

and generated form : 并生成表格:

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

this would save the user document and not save the group_id mention in collection_select, any idea 这将保存用户文档,而不保存在collection_select中提及的group_id,任何想法

Do you use User.new when creating new user or Group.user.create. 创建新用户或Group.user.create时是否使用User.new。 Latter should work. 后应该工作。

this is not a better way but it worked 这不是更好的方法,但是它有效

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

end 结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM