独立Ruby中的活动记录
我有一个独立的Ruby应用程序,希望与ActiveRecordGem一起使用。我制作了3个模型: user.rb独立Ruby中的活动记录,ruby,rails-activerecord,Ruby,Rails Activerecord,我有一个独立的Ruby应用程序,希望与ActiveRecordGem一起使用。我制作了3个模型: user.rb 但现在它填充了数据库,但user_id为null。我在这里遗漏了什么?我不确定,但我认为您不希望在活动记录类中使用这些属性可访问的规范-我认为它们干扰了活动记录自动提供的字段-尝试删除所有这些属性我认为您的评论与帖子相关,而不是与用户相关 只需说docomment1.user=user1然后comment1.save 我认为这里的关键问题是,发表评论的用户不一定就是发表原始帖子的用户
但现在它填充了数据库,但user_id为null。我在这里遗漏了什么?我不确定,但我认为您不希望在活动记录类中使用这些属性可访问的规范-我认为它们干扰了活动记录自动提供的字段-尝试删除所有这些属性我认为您的评论与帖子相关,而不是与用户相关 只需说do
comment1.user=user1
然后comment1.save代码>
我认为这里的关键问题是,发表评论的用户不一定就是发表原始帖子的用户。如果是这种情况,您可以通过through选项强制执行。然而,由于帖子可能会被任何用户评论,那么说post1.comments.create等不应该自动吸引创建帖子的用户,对吗?因为它可能是另一个用户…哪个记录?帖子或评论记录?或者两者都有?你是说数据库中的users
表有一条记录name
为“Joe”
,而state列有“England”
,但是id
列为null?@Stobbej,对于comments表,传递用户是否有效?comment1=post1.comments.create(内容:“这是一篇很棒的文章!”,用户:user1)@Stobbej,它是一样的,对象中为nill,数据库中为null。
require 'active_record'
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :comments
validates :name, :presence => true
attr_accessible :name, :state
end
require 'active_record'
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
validates :title, :length => { :in => 6..40 }
attr_accessible :title, :content
end
require 'active_record'
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
validates :content, :presence => true
attr_accessible :content, :user_id
end
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!"