2012-07-10 34 views
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> 
+0

你也可以发布你的'User'和'Task'模型文件吗?当然是 – paracycle 2012-07-10 12:43:53

+0

!我添加了它们 – cruxi 2012-07-10 12:50:27

+0

请同时添加您的视图的相关部分。 – zsquare 2012-07-10 13:25:12

回答

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

如果你想显示所有的用户名,应该是更沿,如果你有通过查找你的任务,并呼吁它task.usersrails console的关系,可以验证的

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

线。

无论如何,如果您刚刚开始这个项目,我建议您阅读nested resources,因为这是他们的典型用例。

相关问题