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 %>