ユーザーとタスクの間に 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>