jBeas
jBeas

Reputation: 926

rails 3 - associations help

The code below works fine, everything is associated nicely.

However, it's not what I want.

When I am creating a new task I want the task to be associated with the list, and i also what it to have the user_id of the current user. I have added the user_id field to the lists table however, when the form submits the user_id is nil.

If you could please explain how I would need to modify my code to achieve this I would be very grateful.

here is my current setup...

#routes

resources :accounts do
    resources :users do
      resources :lists do
        resources :tasks
      end
    end
  end


#account model
  has_many :users

#user model
  belongs_to :account
  has_many :lists
  has_many :tasks, :through => :lists

#task model
  belongs_to :list

#list model
  belongs_to :user
  has_many :tasks

Upvotes: 1

Views: 46

Answers (1)

drummondj
drummondj

Reputation: 1483

You can probably still nest lists and tasks:

resources :accounts
resources :users
resources :lists do
  resources :tasks
end

Then to save a task for example, in your tasks_controller do:

@list = List.find(params[:list_id])
@task = @list.tasks.new(params[:task])
@task.user = current_user

Assuming you have a method, such as current_user to get the currently logged in user.

Upvotes: 2

Related Questions