I have a has_and_belongs_to_many association between a user and a task.
I wanted a user to join a task and created an action in the user controller as follows:
def joinTask
@user = current_user
@task = Task.find(params[:id])
@users_tasks = @task
@task.save
respond_to do |format|
if @task.update_attributes(params[:task])
format.html { redirect_to [@task.column.board.project, @task.column.board], notice: 'You joined the task successfully' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
To see if that is properly working I wanted to list all users that belong to a specific task. For that I added an action to the user controller where I am trying to get all users that belong to a task:
def showTeam
@users = Task.find(params[:id]).users
respond_to do |format|
format.html # showTeam.html.erb
format.json { render json: @users}
end
end
But I always get the error
undefined method `name' for nil:NilClass
when it tries to render the html page to get the users names...
Am I on the wrong track?
Models:
class Task < ActiveRecord::Base
attr_accessible :description, :title, :weight, :story_id, :column_id, :board_id
belongs_to :story, :foreign_key => "story_id"
belongs_to :column, :foreign_key => "column_id"
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
attr_accessible :name, :login, :email, :password, :password_confirmation, :status
has_and_belongs_to_many :projects
has_and_belongs_to_many :tasks
end
I call the actions:
<%= link_to 'Join task', joinTask_path(task), :class => 'btn' %>
<%= link_to 'Show Team', showTeam_path(task), :class => 'btn' %>
The rootes are defined as follows:
match "joinTask_user/:id" => "users#joinTask", :as => :joinTask
match "showTeam_task/:id" => "tasks#showTeam", :as => :showTeam
And in the end the showTeam.html.erb is rendered and there I want to access the users name:
<p>
<b>Name:</b>
<%= @user.name %>
</p>