これが私の問題です。に行くとProjects#edit
、割り当てられたコースを変更できません。新しいコースを作成しようとしたり、既存のコースから選択しようとすると、次のエラーが表示されます。
Couldn't find Course with ID=23 for Project with ID=62
app/controllers/projects_controller.rb:49:in `update'
{...
"project"=>{"title"=>"Sup",
"due_date"=>"2012-01-23",
"course_id"=>"27", # THIS IS THE ID OF THE NEW COURSE I WANT
"course_attributes"=>{"name"=>"Calc I", # THIS IS THE OLD ONE, I don't need this. Why is it passing this?
"number"=>"MATH102",
"user_id"=>"3",
"id"=>"23"},
"description"=>"bla bla bla"},
"commit"=>"Update Project",
"user_id"=>"3",
"id"=>"62"}
したがって、 を渡そうとしていることはわかりますが、course_attributes
実際には新しい を設定していませんcourse_id
。なぜ渡されているのかわかりませんcourse_attributes
が、他のフォームは空白で、course_attributes
渡されているのは古いコースの属性です。course_id を渡されるように設定したいcourse_id
(この場合は 27)。
プロジェクトコントローラー
def new
@project = @user.projects.new
@courses = @user.courses # Used to populate the collection_select
@project.build_course # I was informed I need to use this to get the form_for to work
end
def edit
@project = Project.find(params[:id])
@courses = @user.courses # Used to populate the collection_select
end
def update
@project = Project.find(params[:id])
@courses = @user.courses
if @project.update_attributes(params[:project])
flash[:notice] = 'Project was successfully updated.'
redirect_to user_projects_path(@user)
else
render :edit
end
end
49 行目は への呼び出しupdate_attributes
です。
その他の情報
project.rb
belongs_to :user
belongs_to :course
attr_accessible :course_id, :course_attributes
accepts_nested_attributes_for :course
course.rb
belongs_to :user
has_many :projects
user.rb
has_many :projects
has_many :courses
したがって、プロジェクトにはデータベースに course_id があります。私は現在、Projects#new ページでその場で既存のコースを作成または選択しています。これが私のフォームです。collection_select と 2 つの text_fields を交互に切り替えるには、JavaScript トグルを使用します。
プロジェクト/new.html.haml
= form_for [@user, @project] do |f|
# This is shown by default
= f.collection_select :course_id, @courses, :id, :name, { prompt: true }
.hidden # This is hidden by default and shown using a toggle
= f.fields_for :course do |builder|
= builder.text_field :name, class: 'large', placeholder: 'Ex: Calculus I'
= builder.label :number, 'Number'
= builder.text_field :number, class: 'new_project_course_number'
= builder.hidden_field :user_id, value: current_user.id
現在、新しいプロジェクト ページにいて、既存のコースを選択してコースに添付すると、正しく機能します。プロジェクトが作成され、正しくcourse_id
設定されます。
新しいプロジェクト ページにいて、JavaScript トグルを使用してコースを作成し、コース名とコース番号を入力して [作成] をクリックすると、それも機能します。コースが作成され、プロジェクトが正しい で作成されますcourse_id
。
長文で申し訳ありませんが、できる限りの情報を提供したいと思います。ありがとう!
更新 1
ルート.rb
resources :users do
resources :projects do
collection do
get 'completed'
match 'course/:course_number' => 'projects#course', as: 'course'
end
end
resources :courses
end