独立 Ruby 中的活动记录

编程入门 行业动态 更新时间:2024-10-24 18:22:14
本文介绍了独立 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 = post1ments.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 选项强制执行它.但是,由于帖子可能会被任何用户评论,那么说 post1ments.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 post1ments.create etc. shouldn't automatically pull in the user who created the post right? Since it might be another user ...

更多推荐

独立 Ruby 中的活动记录

本文发布于:2023-10-27 16:04:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533868.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:独立   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!