0

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

1 に答える 1

0

ユーザーとタスクの間に関係を作成していないようです。

@user = current_user
@task = Task.find(params[:id])
@users_tasks =  @task
@task.save

私はあなたが意味したと思います

@task = Task.find(params[:id])
@task.users << current_user
@task.save

を使用する必要はありませんupdate_attributes。]

また、ショー ビューでは、 をロード@usersしていますが、 を呼び出しています@user.name

すべてのユーザー名を表示したい場合は、次のようにする必要があります

<% @users.each do |user| %>
  <p>
    <b>Name:</b>
    <%= user.name %>
  </p>
<% end %>

rails consoleタスクを見つけて呼び出すことで、関係があるかどうかを確認できますtask.users

いずれにせよ、このプロジェクトを始めたばかりの場合は、タスクのネストされたリソースについて読むことをお勧めします。これはタスクの典型的なユース ケースです。

于 2012-07-10T14:47:14.257 に答える