Creating a category drop down field in Ruby on Rails, using nested forms and has_many :through
Edit: It looks like defining @categories again in the task's create method did the trick of clearing up the error. Still working on actually having the category update when I submit the task, because right now it's ignoring it. Any ideas?
Hi all,
I'm trying to create a drop down list in my first Rails project in order to select from a list of categories for a task. I've used a Categorization model to link the Task model with a Category.
After some effort, I've gotten the drop down to show up properly on the new task form, but when I hit submit, the form gives the following error:
NoMethodError in Tasks#create
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.map
Any help you could provide is really appreciated. Here is the code I'm using (excerpted for brevity)...
The relevant part of my new task form (HAML):
= f.fields_for :categorization do |sub|
= sub.label :name, 'Category'
= sub.collection_select(:category_id, @categories, :id, :name, :include_blank => 'Select a Category')
tasks_controller.rb:
def new
@task = Task.new
@categories = Category.all
end
def create
@task = current_user.tasks.build(params[:task])
if @task.save
flash[:success] = "Task created!"
redirect_to root_path
else
render 'new'
end
end
categorization.rb:
class Categorization < ActiveRecord::Base
belongs_to :task
belongs_to :category
validates :task_id, :presence => true
validates :category_id, :presence => true
end
category.rb:
class Category < ActiveRecord::Base
has_many :categorizations, :dependent => :destroy
has_many :tasks, :through => :categorizations
validates :name, :presence => true
end
task.rb
class Task < ActiveRecord::Base
attr_accessible :title, :body
has_many :categorizations, :dependent => :destroy
has_many :categories, :through => :categorizations
accepts_nested_attributes_for :categorizations
validates :title, :presence => true
validates :body, :presence => 开发者_如何学编程true
end
routes.rb:
resources :tasks
resources :categories do
member do
get :tasks
end
end
Any thoughts? Thank you so much for taking a look, and let me know if you need anything else to help.
Haidn
I think you're going to need to add the following line to your categorization.rb:
attr_accessible :category_id
Without that line, you cannot set the category_id in the build method you are using in tasks_controller.rb
Let me know if that fixes it for you!
OK, I'm going to try figuring out correctly implementing the save on my own, but I discovered the solution for my original problem, which was declaring @categories again in my Task create method. Hopefully that helps somebody!
精彩评论