简体   繁体   English

无法从Rails中的相关模型获取数据

[英]Cannot get data from related models in Rails

I have 2 models in different namespace. 我在不同的命名空间中有2个模型。

class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles
end


class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end

The Membership model is in different folder with AuthorizationRole model (I don't know what is called) 成员资格模型与AuthorizationRole模型位于不同的文件夹中(我不知道叫什么)

When run Admin::Membership.find(:all) , the data from AuthorizationRole model is not included. 运行Admin::Membership.find(:all) ,不包括AuthorizationRole模型中的数据。 I've create membership_id field on authorization_roles table, but I still can't get both models related. 我已经在authorization_roles表上创建了membership_id字段,但是仍然无法使两个模型相关。 Is something wrong in this code? 这段代码有问题吗? Sorry if I'm missing something basic here. 抱歉,如果我在这里缺少一些基本知识。

Try this 尝试这个

class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles, :class_name => '::AuthorizationRole'
end


class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership, :class_name => 'Admin::Membership'
end

I've never used namespaced models and I don't think you need to... but maybe you'll have to specify the class name in AuthorizationRole, something like: 我从未使用过命名空间模型,并且我认为您不需要...但是也许您必须在AuthorizationRole中指定类名称,例如:

belongs_to :membership, :class_name => 'Admin::Membership'

UPDATE: 更新:

Assuming you have: 假设您有:

class Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end

You have added an integer column called membership_id to authorization_roles and you've run the migrations. 您已将一个名为membership_id的整数列添加到authorization_roles,并已运行迁移。 Now you should be able to create authorization_roles like this @membership.authorization_roles.create( ... ) and fetch them @membership.authorization_roles 现在,您应该能够像这样@membership.authorization_roles.create( ... )创建authorization_roles并通过@membership.authorization_roles获取它们

Check to see if you are setting the table name prefix. 检查是否要设置表名前缀。 The Rails model generator adds a file like this for namespaced models: Rails模型生成器将为命名空间模型添加一个如下文件:

# /app/models/admin.rb
module Admin
  def self.table_name_prefix
    'admin_'
  end
end

Note: this is Rails version 3.0.1 -- not sure about earlier versions. 注意:这是Rails 3.0.1版-不确定较早的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM