独立 Ruby 中的活动记录 [英] Active record in standalone Ruby
问题描述
我有一个独立的 Ruby 应用程序,并希望将它与活动记录 gem 一起使用.我做了3个模型:用户.rb
I have standalone Ruby application and want to use it with active record gem. I've made 3 models: user.rb
require 'active_record'
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :comments
validates :name, :presence => true
attr_accessible :name, :state
end
post.rb
require 'active_record'
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
validates :title, :length => { :in => 6..40 }
attr_accessible :title, :content
end
comment.rb
require 'active_record'
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
validates :content, :presence => true
attr_accessible :content, :user_id
end
现在我想通过发出以下代码为该帖子和用户填充一个用户、一个帖子和一个评论:
Now I want to populate database with one user, one post and one comment for this post and user by issuing this code:
require 'active_record'
require 'sqlite3'
require './models/user'
require './models/post'
require './models/comment'
ActiveRecord::Base.configurations = YAML::load(IO.read('config/database.yml'))
ActiveRecord::Base.establish_connection("development")
user1 = User.create name: "Joe", state: "England"
post1 = user1.posts.create title: "RoR introduction", content: "RoR intro."
comment1 = post1.comments.create content: "This is great article!"
但现在它填充了数据库但 user_id 为空.我在这里错过了什么?
But now it populates database but user_id is null. What am I missing here?
推荐答案
我认为您的评论与帖子相关联,而不是与用户相关联......
I think that your comment gets associated with a post, and not a user ...
只需说 do comment1.user = user1
然后 comment1.save!
just say do comment1.user = user1
and then comment1.save!
我认为这里的关键问题是发表评论的用户不一定是发表原始帖子的用户.如果是这种情况,您可以通过 through 选项强制执行它.但是,由于帖子可能会被任何用户评论,那么说 post1.comments.create 等不应该自动拉入创建帖子的用户,对吗?因为它可能是另一个用户...
I think the key issue here is that the user making the comment is not necessarily the user who made the original post. If that were the case you could enforce it via the through option. However since a post may be commented upon by any user, then saying post1.comments.create etc. shouldn't automatically pull in the user who created the post right? Since it might be another user ...
这篇关于独立 Ruby 中的活动记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!