1

我在这个问题上停留了几天..请帮助,在此先感谢。

这是一个 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"]}

我错过了什么?

4

1 回答 1

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
于 2013-09-16T02:14:37.907 回答