Active record in standalone Ruby

假装没事ソ 提交于 2019-12-13 15:17:57

问题


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!"

But now it populates database but user_id is null. What am I missing here?


回答1:


I think that your comment gets associated with a post, and not a user ...

just say do comment1.user = user1 and then comment1.save!

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 ...




回答2:


I'm not sure but I don't think you want those attr_accessible specifications in an active record class - I think they are interfering with the fields that active record provides automatically - try removing all of them



来源:https://stackoverflow.com/questions/15930644/active-record-in-standalone-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!