mongoid无法在轨道中推动HABTM关系

时间:2012-11-14 01:44:55

标签: ruby-on-rails mongoid

我几天坚持这个问题。请提前帮助,谢谢。

这是mongoid上的rails项目,项目中有2个模型,一个是User,另一个是CustomSearchEngine:

class User
  include Mongoid::Document
  # Include default devise modules. Others available are:
  ......
  # keep the CSEs
  has_and_belongs_to_many :keeped_custom_search_engines, class_name: 'CustomSearchEngine', inverse_of: :consumers

  # create or fork the CSEs
  has_many :custom_search_engines, inverse_of: :author, dependent: :destroy

  # Index
  index({username: 1}, {unique: true, name: 'user_username'})
  index({email: 1}, {unique: true, name: 'user_email'})

  # Massive assignment for User.new
  attr_accessible :email, :username, :agreement, :password, :password_confirmation
  attr_accessor :agreement, :password_confirmation
  validates :password_confirmation, presence: true
  validates :agreement, presence: true
end

class CustomSearchEngine
  include Mongoid::Document
  include Mongoid::Timestamps
  paginates_per 20
 ...
  belongs_to :author, class_name: 'User', inverse_of: :custom_search_engines
  has_and_belongs_to_many :consumers, class_name: 'User', inverse_of: :keeped_custom_search_engines
  belongs_to :node

  # Index
  index({author_id: 1}, {name: 'cse_author_id'})
  index({node_id: 1}, {name: 'cse_node_id'})

  # validations
  validates :status, presence: true, inclusion: {in: ['draft', 'publish']}
  validates :author_id, presence: true
  validates :node_id, presence: true

  scope :recent, ->(status) { where(status: status).desc(:created_at) }
  ...
end

在我的CustomSearchEngine控制器中:

current_user.keeped_custom_search_engines.push(@custom_search_engine)

然后我去了我的mongodb,我看到只更新了用户文档:

keeped_custom_search_engine_ids: ["50a208092061c770190000df"]

但自定义搜索引擎文档未更改:

consumer_ids: [] 

我收到错误:@messages={:consumers=>["is invalid"]}

我错过了什么?

1 个答案:

答案 0 :(得分:0)

我认为这个问题是你在消费者实例保存到数据库之前推动消费者。

尝试这样的代码:

  def create
@team = Team.new(params[:team])
@team.own = current_user
respond_to do |format|
  if @team.save
    current_user.push_join_teams(@team.id)
    format.html { redirect_to @team, notice: 'Team was successfully created.' }
    format.json { render json: @team, status: :created, location: @team }
  else
    format.html { render action: "new" }
    format.json { render json: @team.errors, status: :unprocessable_entity }
  end
end
end

#user.rb
def push_join_teams(tid)
 return false if self.join_team_ids.include?(tid)
 self.push(:join_team_ids,tid)
end