代码之家  ›  专栏  ›  技术社区  ›  Barry Hess

轨道3,有许多:通过和<<运算符

  •  0
  • Barry Hess  · 技术社区  · 15 年前

    将应用程序转换为Rails3。遇到了这个缺失的语法糖。

    class Group < ActiveRecord::Base
      has_many :memberships
      has_many :users, :through => :memberships
    end
    
    class Membership < ActiveRecord::Base
      belongs_to :group
      belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_many :memberships
      has_many :groups, :through => :memberships
    end
    

    在Rails 3中我不能再这样做了:

    $ group = Group.first
    $ user = User.first
    $ group.users << user
    ActiveRecord::StatementInvalid: Mysql2::Error: Column 'user_id' cannot 
    be null: INSERT INTO `memberships` (`admin`, `created_at`, 
    `group_id`, `leader`, `updated_at`, `user_id`) VALUES 
    (0, '2010-11-03 18:31:33', 5, 0, '2010-11-03 18:31:33', NULL)
    

    去哪了 << 走吧?它被什么东西取代了吗?

    2 回复  |  直到 15 年前
        1
  •  0
  •   Kevin    15 年前

    这里有<<方法。错误来自MySQL。你真的是用现有的记录做的吗?

        2
  •  0
  •   Barry Hess    15 年前

    密钥丢失信息。我有一个初始化程序,它执行以下操作以强制对我的模型执行保护状态:

    ActiveRecord::Base.send(:attr_accessible, nil)
    

    在这种情况下,成员类实际上需要如下所示:

    class Membership < ActiveRecord::Base
      belongs_to :group
      belongs_to :user
      attr_accessible :user_id, :group_id
    end
    

    基本上,Rails内部不能访问Rails 3之前的受保护属性。