Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
独立Ruby中的活动记录_Ruby_Rails Activerecord - Fatal编程技术网

独立Ruby中的活动记录

独立Ruby中的活动记录,ruby,rails-activerecord,Ruby,Rails Activerecord,我有一个独立的Ruby应用程序,希望与ActiveRecordGem一起使用。我制作了3个模型: user.rb 但现在它填充了数据库,但user_id为null。我在这里遗漏了什么?我不确定,但我认为您不希望在活动记录类中使用这些属性可访问的规范-我认为它们干扰了活动记录自动提供的字段-尝试删除所有这些属性我认为您的评论与帖子相关,而不是与用户相关 只需说docomment1.user=user1然后comment1.save 我认为这里的关键问题是,发表评论的用户不一定就是发表原始帖子的用户

我有一个独立的Ruby应用程序,希望与ActiveRecordGem一起使用。我制作了3个模型: user.rb


但现在它填充了数据库,但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!"