新手问题 rails 下新建一个 blog 模板的问题

Yunich · 2012年12月20日 · 最后由 QueXuQ 回复于 2012年12月20日 · 3171 次阅读

我新建了一个 rails 项目,在下面建了一个新 Model 为Topic然后添加一个关联 Model Tag ,启动 sever 后,我发现Tag是不能编辑的,于是我想在 rails console 里面写入值,我的Tag这样写的

class CreateTags < ActiveRecord::Migration
  def change
    create_table :tags do |t|
      t.string :name
      t.references :topic

      t.timestamps
    end
    add_index :tags, :topic_id
  end
end

我在 console 里应该怎样命令呢 Tag.create(name:'ruby',topic:' ')这样子的对么

Tag.new(name:'ruby',topic:' ') 好像是这样吧。

@我其实是想问后面topic:后面该怎么写的

可以这样创建关联的吗? t.references :topic这样不太清楚。 如果是我的话,我是这样建的:

class CreateTags < ActiveRecord::Migration
  def change
    create_table :tags do |t|
      t.string :name
      t.integer :topic_id

      t.timestamps
    end
    add_index :tags, :topic_id
  end
end

然后我要创建一个关联于 topic 为 1 的 tag 的话:

Tag.create(name:'ruby',topic_id:1)

参考:http://ihower.tw/rails3/activerecord-relationships.html

# 给现有 topic 加 tag
topic = Topic.find id
Tag.create :name => 'tagname', :topic => topic

@QueXuQ 谢谢你提供的这种方法,其实就是想问下references应该怎么写

references 是 Migration 用的,在 Model 和 Controller 里就像 @Rei 说的那样写;建议先系统看看 ROR 的 DOC http://guides.rubyonrails.org/

#6 楼 @Magic 我想问下:

t.references :topic
t.integer :topic_id

两种写法是不是等价的?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号