我有两个模型:用户和语言模型。一个用户可以使用三种不同的语言。我想向用户展示一种语言。
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:facebook]
has_many :messages, dependent: :destroy
has_many :pictures, dependent: :destroy
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
belongs_to :first_language, class_name: 'Language'
belongs_to :second_language, class_name: 'Language'
belongs_to :third_language, class_name: 'Language'
end
class Language < ActiveRecord::Base
has_many :users, foreign_key: "first_language_id"
# How to do the same with second and third language ?
end
对于语言控制器,我不知道如何找到说(第一,第二或第三语言)语言的用户!
class LanguagesController < ApplicationController
before_action :authenticate_user!
before_action :find_language, only: :show
def show
@users = @language.users
# How to select the users who speak first, second or third language ?
end
private
def find_language
@language = Language.find(params[:id])
end
end
用户架构:
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "provider"
t.string "uid"
t.string "picture"
t.string "first_name"
t.string "last_name"
t.string "token"
t.datetime "token_expiry"
t.integer "first_language_id"
t.integer "second_language_id"
t.integer "third_language_id"
t.string "description"
end
语言架构:
create_table "languages", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
答案 0 :(得分:0)
class User < ActiveRecord::Base
belongs_to :first_language, class_name: 'Language'
belongs_to :second_language, class_name: 'Language'
belongs_to :third_language, class_name: 'Language'
end
class Language < ActiveRecord::Base
has_many :users
end
您可以通过
访问特定语言的用户@language.users