0
我在用户和任务之间有一个has_and_belongs_to_many关联。如何从Rails 3中的连接表中访问数据
我想用户加入任务,并在用户控制器创建的动作如下:
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>
你也可以发布你的'User'和'Task'模型文件吗?当然是 – paracycle 2012-07-10 12:43:53
!我添加了它们 – cruxi 2012-07-10 12:50:27
请同时添加您的视图的相关部分。 – zsquare 2012-07-10 13:25:12