我在用户和任务之间有一个 has_and_belongs_to_many 关联。
我希望用户加入任务并在用户控制器中创建一个操作,如下所示:
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
为了查看这是否正常工作,我想列出属于特定任务的所有用户。为此,我向用户控制器添加了一个操作,我试图在其中获取属于某个任务的所有用户:
def showTeam
@users = Task.find(params[:id]).users
respond_to do |format|
format.html # showTeam.html.erb
format.json { render json: @users}
end
end
但我总是得到错误
undefined method `name' for nil:NilClass
当它尝试呈现 html 页面以获取用户名时...
我在错误的轨道上吗?
楷模:
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
我称之为行动:
<%= link_to 'Join task', joinTask_path(task), :class => 'btn' %>
<%= link_to 'Show Team', showTeam_path(task), :class => 'btn' %>
根定义如下:
match "joinTask_user/:id" => "users#joinTask", :as => :joinTask
match "showTeam_task/:id" => "tasks#showTeam", :as => :showTeam
最后呈现 showTeam.html.erb 并且我想访问用户名:
<p>
<b>Name:</b>
<%= @user.name %>
</p>