簡體   English   中英

Rails:如何設置活動記錄關聯?

[英]Rails: How to set up Active Record Associations?

我對Rails比較陌生,並且做的最簡單:關聯用戶和帖子。 我讀過這篇文章 ,但是要使它正常工作(或者這是唯一的事情),我還需要做些什么?

class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
end

class Post < ActiveRecord::Base
  belongs_to :user
end

更新:我無法使其正常工作。 當我使用已登錄的用戶發布帖子時,我執行@user.posts.any?時會@user.posts.any? 在控制台中。 我的代碼:

post.rb

class Post < ActiveRecord::Base
  attr_accessible :title, :user_id
  belongs_to :user
  before_create :default_values

user.rb(我使用devise)

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me
  has_many :posts, dependent: :destroy
end

20130320162700_create_posts.rb

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.integer :user_id

      t.timestamps
    end
  end
end

您應該確保在創建posts表的遷移中包括用戶ID。 在您的遷移文件中(在db / migrate文件夾中,您將找到一個名為20130325105934_create_posts.rb的文件)

在文件中,您將找到遷移代碼。 連同其他聲明的屬性一起添加

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
     ...... 
     t.integer :user_id
     ......
  end

結束

它應該足以使事情滾動:-)

在您的代碼內,然后您可以創建一個新用戶

@user = User.new(:login => "my_user", .....)

然后使用以下兩種方法之一添加帖子(還有其他兩種方法)。

post = Post.new(:title => "something", :text => "more of something", :user_id = @user.id)

要么

   post = Post.new(:title => "something", :text => "more of something")
   @user.posts << post

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM