[英]Using has_many through associations in Rails 4
我正在尝试在Rails 4应用程序中创建一些简单的关系。 我有三种模型: user , list , word 。
这是用于简单的“列表”应用程序,其中每个用户在列表中有很多单词。
我目前有以下关联...
用户模型:
class User < ActiveRecord::Base
has_many :words through :lists
end
清单型号:
class List < ActiveRecord::Base
has_many :words
belongs_to :user
end
单词模型:
class Word < ActiveRecord::Base
belongs_to :list
end
我不确定如何通过控制台创建关系。 例如...
> user = User.create(name: "Kyle")
> list = List.create(name: "List One")
> word = Word.create(word: "StackOverflow")
>
> list.push(word) # add word to list
> user.push(list) # add list to user
有人可以举例说明如何正确创建这些关联。
class User < ActiveRecord::Base
has_many :lists
has_many :words, through: :lists
end
class List < ActiveRecord::Base
has_many :words
belongs_to :user
end
class Word < ActiveRecord::Base
belongs_to :list
end
> user = User.create(name: "Kyle")
> list = List.create(name: "List One")
> word = Word.create(word: "StackOverflow")
# Add word to a list
> list.words << word
> list.words.create(word: "LinkedIn") # Add a newly created word directly
> list.words << Word.find(params[:word_id]) # Add an existing word after finding it by its id
# Associate a list to a user
> user.lists << list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.