Ruby on Rails 协会新手 [英] ruby on rails associations newbie

查看:34
本文介绍了Ruby on Rails 协会新手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能被认为是对 rails 3 关联错误的重新发布.但它的东西我无法理解.但是好吧......这是交易......我在这里问了一个与表模式相关的问题.帖子是这个表架构结构有什么不好 和查询是:

This might be considered as a re-post of rails 3 associations error. But its something which I am not able to understand . But ok ... heres the deal.. I have asked a question in here which was related to a table schema. The post is what is bad in this table schema structure and the query was :

`CREATE TABLE "pages" (
   "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
   "title" varchar(255),
   "body" varchar(255),
   "author" varchar(255), 
   "email" varchar(255), 
   "reference" varchar(255),
   "created_at" datetime,
   "updated_at" datetime);`

有人建议我为作者创建单独的表格,这就是我尝试并搞砸的.谁能告诉我这些关联究竟应该如何与我的场景配合使用?我真的需要很好地理解 ROR 关联.

I was suggested that I should create separate tables for author, and that is what I tried and messed up. Can anyone please tell me how exactly should the associations work with my scenario? I really need to understand the ROR associations well.

这是我的页面迁移代码:

Here is my pages migration code:

class CreatePages < ActiveRecord::Migration
  def self.up
    create_table :pages do |t|
      t.string :title, :unique => true, :limit => 50
      t.string :body, :limit =>255
      t.string :email, :unique => true, :limit => 50
      t.string :reference, :limit => 40
      t.timestamps
    end
    
  end

  def self.down
    drop_table :pages
  end
end

这是我的作者迁移:

class CreateAuthors < ActiveRecord::Migration
  def change
    create_table :authors do |t|
      t.string :author, :unique => true, :null => false, :limit => 50
      t.timestamps
    end
  end
end

推荐答案

为作者创建一个单独的表可能是一个好主意(尽管如果这对你来说已经很好用,并且你没有任何性能问题,你可以保持原样).

Creating a separate table for authors is probably a good idea (although if this working well for you already, and you don't have any performance problems, you could just leave it as is).

@Marc Talbot 已经就如何在 Rails 模型中设置关联给出了很好的答案.当然,您还需要迁移数据库.这样做:

@Marc Talbot already gave a good answer about how to set the associations up in your Rails models. Of course, you will also need to migrate your database. This is what to do:

  1. 制作一个名为authors"的表格.除了主键id"之外,它还应该有一个名为name"的字段,以及email".您可以将同一作者在逻辑上始终相同的任何其他字段从页面"移动到作者".
  2. 向pages"添加一个整数字段author_id".
  3. 遍历页面"中的现有条目.对于每个页面,检查作者是否已经在作者"中.如果不是,将作者添加到authors"中,并在authors"中填写name"、email"和其他字段.设置author_id"以引用作者表中的正确 ID.
  4. 从页面"中删除作者"、电子邮件"和其他移动的字段.

这篇关于Ruby on Rails 协会新手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆