Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在Rails 3中从联接表中访问数据_Ruby_Ruby On Rails 3_Has And Belongs To Many - Fatal编程技术网

Ruby 如何在Rails 3中从联接表中访问数据

Ruby 如何在Rails 3中从联接表中访问数据,ruby,ruby-on-rails-3,has-and-belongs-to-many,Ruby,Ruby On Rails 3,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]) for

我在用户和任务之间有很多关联

我希望用户加入任务,并在用户控制器中创建了一个操作,如下所示:

  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
match "joinTask_user/:id" => "users#joinTask", :as => :joinTask
match "showTeam_task/:id" => "tasks#showTeam", :as => :showTeam
为了查看这是否正常工作,我想列出属于特定任务的所有用户。为此,我向用户控制器添加了一个操作,尝试获取属于某个任务的所有用户:

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
最后呈现showTeam.html.erb,我想在那里访问用户名:

<p>
  <b>Name:</b>
  <%= @user.name %>
</p>

姓名:


您似乎从未在用户和任务之间建立关系

@user = current_user
@task = Task.find(params[:id])
@users_tasks =  @task
@task.save
我想你的意思是

@task = Task.find(params[:id])
@task.users << current_user
@task.save
您可以通过查找您的任务并在其上调用
task.users
来验证您在
rails控制台中是否存在关系


在任何情况下,如果您刚刚开始这个项目,我建议您继续阅读您的任务,因为这是它们的典型用例。

您是否也可以发布您的
用户
任务
模型文件。请添加视图的相关部分。
@task = Task.find(params[:id])
@task.users << current_user
@task.save
<% @users.each do |user| %>
  <p>
    <b>Name:</b>
    <%= user.name %>
  </p>
<% end %>