王筝的博客
ruby学习

新开了个项目,数据库打算只用mysql,但是在migrate的时候失败,并且提示err: mongoid[not found]

原因就是在Gemfile里写了一个有关mongoid的gem,搜索并删除就好了。

一个rails项目如何连多个mongo数据库呢,答案在这里

http://stackoverflow.com/questions/16400458/connecting-to-two-databases-mongoid

 

(1)先在config/mongoid.yml配置一下

development:
  sessions:
    default:
      database: ott_tv_cms_development
      hosts:
        - localhost:27017
      options:
    live:
      database: ott_tv_live_cms_development
      hosts:
        - localhost:27017
      options:

  options:

这是development的环境,其他的也一样呢,在session下面新增个数据库链接就行

 

(2)在对应的model里增加链接配置信息

就是那句store_in

class LiveChannel
  include Mongoid::Document
  include Timestamps

  store_in session: "live", collection: 'live_channel'

  field :logo, type: String
  field :name, type: String
  field :channel, type: String

  has_many :live_videos, primary_key: 'channel', foreign_key: 'channel'
end

搞定啦~

 

 

How to use the like query with Mongoid . Basically I wanted something like the familiar SQL query:

SELECT * FROM Apps WHERE name LIKE ‘%aaa%’

I couldn’t find anything similar in the Mongoid documentation, but according to the MongoDB documentation you can do regex searches.

Apps.where(name: /aaa/)

Package.where(title: /博影/).first

title = “博影”

Package.where(title: /#{title}/)

注意这行语句在vim里会被误导,vim会把#以后的当作注释,忽略这一点啊.不影响执行效果

现在觉得mongoid很优雅啊,哈哈.

http://mongoid.org/en/mongoid/docs/querying.html#queries

http://docs.mongodb.org/manual/reference/operator/query-comparison/

gt大于, gte大于等于,lt小于, lte小于等于,inc自增或自减

if old_position > new_position
@packages = Package.where(:type => params[:package][:type])
.where(:is_actived => true)
.where(:position.gte => new_position)
.where(:position.lt => old_position).inc(position: 1)
elsif new_position > old_position
@packages = Package.where(:type => params[:package][:type])
.where(:is_actived => true)
.where(:position.lte => new_position)
.where(:position.gt => old_position).inc(position: -1)
end

——————————————–

def adjust_same_type_actived_packages_position(old_position)
return if position == old_position

if position < old_position
Package.actived.not_in(_id: [id]).
where(:type => type,
:position.gte => position,
:position.lt => old_position).inc(position: 1)
else
Package.actived.not_in(_id: [id]).
where(:type => type,
:position.lte => position,
:position.gt => old_position).inc(position: -1)
end
end

 

 //由于这是model里的实例方法,[id]就是实例的id