2011-11-02 111 views
0

我开始在Rails中使用数据库关联的全部(奇妙)概念,但是我遇到了问题,因为我正在使用不符合Rails标准的现有数据库并且无法计算了解如何命名这些关联。有几个类似的帖子,但如下我不能换我的头周围命名为我的具体情况是:Ruby on Rails协会澄清

table book with book.formatId looks up values in book_format.id 

所以外键book.formatId

我的车型被命名为: Book和BookFormat(我读过你使用camelCase,当你的表用下划线分隔时)。

下Book模型我有这样的:

has_one :bookFormat, :foreign_key => 'book_format.id' # not sure if this format table.field is correct or I have to use something else here. Also not sure about the bookFormat, should it be BookFormat or bookformat? 

的BookFormat模型具有这样的:

belongs_to :book 

但是,当我尝试做

book = Book.first 
book.bookFormat.empty? 

我得到的错误未找到bookFormat方法。所以显然有些问题,但我无法弄清楚在哪里。

问题的第二部分是使用多对多的关系。例如:

表 书,book_subjects,book_subjects2title

book_subjects.id => book_subjects2title.pId book.id => book_subjects2title.bookId

我Apress出版读取开始Rails 3的书(这是一本很棒的书),但这并不是很清楚,或者我只是没有得到它。

谢谢。

回答

0

由于书店就可以了formatId,你应该使用belongs_to的,并更改外键这样:

belongs_to :book_format, :class_name => 'BookFormat', :foreign_key => 'formatId' 

表名,我做了一些快速搜索,发现下面的方法: set_table_name

所以,你应该能够在其模型的顶部添加,像这样:

class Book < ActiveRecord::Base 
    set_table_name 'book' 
    # the rest of book model code 
end 

class BookFormat < ActiveRecord::Base 
    set_table_name 'book_format' 
    # rest of book_format model code 
end 

常轨使用复数表名,所以为什么你需要在那里指定它。

+0

我会尝试一下你的建议,但是只是想说,为了防止rails使用你的复数,把它放到config/application.rb文件中:'config.active_record.pluralize_table_names = false'并且工作时不需要明确设置表名。在leas Book.first的作品中,查询正确的表格。 – kakubei

+0

我按照你的建议完成了,但我仍然收到找不到方法的错误。因此,澄清,'belongs_to:book_format'(book_format是表的名称,是吗?), 然后我使用call book.bookformat.empty?是BoookFormat,book_format还是bookformat?我在这里使用了什么? – kakubei

+0

对于在何处使用表名以及在何处使用类名称,我仍然很困惑,为什么我们使用小写的类名(如果它们实际上是用大写字母来创建的)。我知道,如果你遵循rails的准则,并为你创建表格,那么一切似乎都会更好,但不幸的是,对于我来说,我不得不与现有的数据库搏斗。 – kakubei

0

agmcleod把我在正确的轨道上,所以这里的在希望的完整的答案,这可以帮助其他人有类似问题:

我创建了一个不同的名称,型号,方便阅读。因此,模型书籍将拥有:

class Books < ActiveRecord::Base 
    set_table_name 'bookpedia' 
    belongs_to :format, :foreign_key => 'formatId' # we need to specify the foreign key because it is not the rails default naming 
    has_many :author2title, :foreign_key => 'bookId' 
    has_many :author, :through => :author2title 
end 

模型格式:

class Format < ActiveRecord::Base 
    set_table_name 'book_format' 
    has_many :books 
end 

然后类的实例将有格式的方法:

@book = Books.first 
@book.format # Hardcover 

对于多对多的关系,我会粘贴这里的语法,因为这花了我一段时间才弄清楚:

class Author < ActiveRecord::Base 
    set_table_name 'book_author' 
    has_many :author2title, :foreign_key => 'pId' # junction table 
    has_many :books, :through => :author2title # establishing the relationship through the junction table 
end 

这是实际的结合表:

class Author2title < ActiveRecord::Base 
    set_table_name 'book_author2title' 
    belongs_to :author, :foreign_key => 'pId' # foreign key needs to be here as well 
    belongs_to :books, :foreign_key => 'bookId' 
end 

上面的书模型对这种多对多的关系已经在它必要的条目。

如果有人需要澄清这一点,我会很乐意承担义务,因为我挣扎了一天多的时间才弄明白这一点,所以很乐意提供帮助。

干杯。

+0

很高兴你找到答案! – agmcleod