Как создать экземпляр связанной модели при использовании ассоциации has_many:through
У меня есть две модели (Called User и Plan), которые я связал с помощью has_many: через ассоциацию (называемую Участие). План должен быть создан пользователем, и поэтому я хочу знать:
Как создать экземпляр модели Plan и экземпляр модели соединения. Участие с помощью доступа к методу create через экземпляр модели User.
На данный момент я просто пытаюсь заставить его работать в консоли rails, но, конечно, я хочу использовать функциональность в моем приложении. Я не использую ассоциацию HABTM, потому что следующим шагом является добавление атрибута в отношение.
Я могу получить доступ к существующим экземплярам плана, введя
> User.first.plans.all
в консоль Rails. но когда я пытаюсь либо
> User.first.plan.new
или же
> User.first.plans.new
или же
> User.first.plan.create
или же
> User.first.plans.create
Я получаю сообщение об ошибке
NoMethodError: undefined method `plan' for #<User:
или же
NoMethodError: undefined method `plans' for #<User:
Дополнительная информация: соответствующие модели:
class User < ActiveRecord::Base
has_many :participations #, :foreign_key => ":user_id"
has_many :plans, :through => :participations
accepts_nested_attributes_for :participations, :plans
end
class Plan < ActiveRecord::Base
has_many :participations #, :foreign_key => ":plan_id"
has_many :users, :through => :participations
accepts_nested_attributes_for :participations, :users
end
class Participation < ActiveRecord::Base
belongs_to :user #, inverse_of: :participations
belongs_to :plan #, inverse_of: :participations
validates :user_id, presence: true
validates :plan_id, presence: true
end
схема есть:
create_table "participations", force: :cascade do |t|
t.integer "user_id", null: false
t.integer "plan_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "participations", ["plan_id"], name: "index_participations_on_plan_id", using: :btree
add_index "participations", ["user_id"], name: "index_participations_on_user_id", using: :btree
create_table "plans", force: :cascade do |t|
t.text "title"
t.text "description"
t.text "plan_type"
t.datetime "start_date"
t.datetime "end_date"
t.integer "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "plans", ["parent_id"], name: "index_plans_on_parent_id", using: :btree
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 "username", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree
end
1 ответ
Этим утром я смог использовать User.first.plans.new
а также User.first.plans.create
создать новый экземпляр плана. Мое единственное предположение, что перезапуск консоли рельсов сделал свое дело. Я уверен, что сделал это до того, как опубликовал вышеуказанный вопрос.
@ MilesStanfield: Спасибо! Из-за вашего комментария я дважды проверил все. После этого я подумал дать еще одну попытку.