我正在努力建立一种我认为理解的一对一关系......
我的用户表和配置文件表应该与一对一的关系链接,但是当我尝试调用它时,它会返回错误。
以下是我的模特:
class Profile < ApplicationRecord
mount_uploader :AvatarUploader
belongs_to :user
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
acts_as_voter
enum role: [:user, :admin]
has_many :entries, dependent: :destroy
has_many :reports, dependent: :destroy
has_many :messages
has_one :profile
end
我的架构中的相关表格:
create_table "profiles", force: :cascade do |t|
t.text "bio"
t.string "avatar"
t.string "country"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_profiles_on_user_id"
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.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "role", default: 0
t.integer "score", default: 0
t.string "username"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
所以我试图调用user.country,它返回no方法错误。我已经阅读了几个不同网站上的关系,但似乎无法注意到我做错了什么
由于
答案 0 :(得分:1)
您的所有关联设置都是正确的,但我认为您稍微误解了rails中关联的工作方式。由于您拥有关联local background = display.newImageRect("blueBackground.png",642, 1040)
background.x = display.contentCenterX
background.y = display.contentCenterY
local x = 15
local y=15
for i=15,25 do
for j=15, 25 do
local bubble = display.newImageRect("bubble.png", 23,23)
bubble.x = i
bubble.y = j
j = j + 29
print("j",j)
end
i = i + 29
print("i",i)
end
和user has_one profile
您可以调用profile belongs_to user
,它将返回与用户关联的配置文件对象。要访问个人资料中的@user.profile
属性,您必须实际调用country
。所以不要打电话
@user.profile.country
你必须使用
user.country
希望这有帮助。
答案 1 :(得分:1)
通常你会想要打电话
user.profile.country
但是如果您想使用user.country
,则必须将这些方法从Profile
委托给User
,如下所示:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
acts_as_voter
enum role: [:user, :admin]
has_many :entries, dependent: :destroy
has_many :reports, dependent: :destroy
has_many :messages
has_one :profile
#delegate method call to profile, check the delegate document for more options.
delegate :country, to: :profile
end