0

私は Rails に不慣れで、基本的に他の人たちと同じ疑問を抱いています。2 つのテーブルを相互にリンクしたいと考えています。しかし、私はそれをすることができませんでした。強力なスタックオーバーフロー ユーザーを助けてください。

ユーザー クラス:

class User < ActiveRecord::Base
  attr_accessible :password, :username, :oauth_token, :provider, :uid, :oauth_expires_at, :picture, :email, :name, :location, :gender, :updated_at, :is_admin
  has_many :posts   
end

投稿クラス:

class Post < ActiveRecord::Base
  attr_accessible :details, :title, :user_id, :picture
  belongs_to :user
end

ターミナルで Rails コンソールにログインし、次のように言います。

@allusers = Users.all
@allposts = Users.Posts.all

そして、エラーが発生します。これらのテーブルをリンクする他の方法またはRubyコードはありますか?

4

3 に答える 3

5

結果として何を望むかによって異なります。

@allusers = User.all # returns all users of the users table
@allposts = Post.all # returns all posts of the posts table
@user = User.first # returns first user of the users table
@posts = @user.posts # returns all posts of the first user of the posts table
@posts = User.first.posts # also returns all posts of the first user of the posts table

クエリの詳細については、次を参照してください。

アップデート

@posts = User.where(:id => 123).first.posts # returns all posts of the user with the id 123. => all posts of the posts table which have the user_id 123 will be returned.

current_user メソッドがある場合 => 現在ログインしているユーザーを返す場合、次の方法で彼の投稿を簡単に取得できます。

@posts = current_user.posts
于 2013-05-10T11:41:20.013 に答える