【问题标题】:Updating a document that has both belongs_to and has_many associations更新同时具有belongs_to 和has_many 关联的文档
【发布时间】:2015-06-18 20:02:42
【问题描述】:

每当我更新我的文档时,我的 Rails/Mongoid 应用程序都会出现问题。

我有三个集合:ownersvesselsmodifications

class Owner
    include Mongoid::Document
    has_many :vessels
    field :name, type: String
    field :uprn, type: String
end

class Vessel
    include Mongoid::Document   
    belongs_to :owner
    has_many :modifications
    field :name, type: String
    attr_accessor :uprn
end

class Modification
    include Mongoid::Document   
    belongs_to :vessel  
    field :change_description, type: String
end

这个想法是每个船东拥有几艘船(has_manybelongs_to 关系正在进行)并且对每艘船进行了多次修改(同样,has_manybelongs_to 关系) .

创建所有者、容器和更改工作正常。当我尝试更新所有者时,它可以工作。如果我尝试更新修改,它也可以工作。但是,当我尝试更新属于所有者的船只并对其进行一些修改时,我收到了以下错误:

OwnersController#update 中的 NoMethodError

#Mongoid::Criteria:0xb50d49d0 的未定义方法“值”

这是引发此错误的代码。除了只修改存储在文档中的数据,它还检查所有者是否改变(这就是 uprn 字段的来源)并相应地改变 owner_id。

def update
    @vessel = Vessel.find(params[:id])
    @owner = Owner.find_by(uprn: params[:vessel][:uprn])
    if @owner.present?
        @vessel.owner_id = @owner.id
        if @vessel.update(vessel_params)
            redirect_to @vessel
        else
            render 'edit'
        end
    else
        @vessel.errors[:base] << "There is no owner with the UPRN entered."
        render 'edit'
    end
end

请注意,这仅在两者之间存在 1-n 关联时才会发生。如果每艘船只有一个修改(所以has_onebelongs_to 关联)它工作得很好。如果我尝试嵌入,同样的处理 - 1-1 嵌入更新正常,1-n 嵌入报告相同的错误。如果只有船只及其改装件(与所有者无关),它也可以正常工作。当船只与所有者及其修改相关联时,就会发生这种情况。

我正在使用 Ruby 1.9.3、Rails 4.2.1、Mongo 2.6.1 和 Mongoid 4.0.2。

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid nomethoderror


    【解决方案1】:

    显然解决此问题的方法是从 Owner 中删除 has_many :vessels 并从 Vessel 中删除 has_many: modifications,以便生成的代码如下所示:

    class Owner
        include Mongoid::Document
        field :name, type: String
        field :uprn, type: String
    end
    
    class Vessel
        include Mongoid::Document   
        belongs_to :owner
        field :name, type: String
        attr_accessor :uprn
    end
    
    class Modification
        include Mongoid::Document   
        belongs_to :vessel  
        field :change_description, type: String
    end
    

    删除这两行后,应用就可以正常工作了。

    【讨论】:

      【解决方案2】:

      问题似乎是字段名称,如果任何字段包含“更改”一词,则会出现错误。希望这对其他人有帮助。

      【讨论】:

      • 嗨,欢迎来到 SO。这实际上应该是评论,而不是答案。一旦您获得足够的声誉,您就可以发表评论。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      相关资源
      最近更新 更多