0

我正在制作一个模型,其中用户可以属于多个团队并且团队有多个人。我有复选框,但它们不会将值传递给对象。

class User < ActiveRecord::Base
  attr_accessible :email, :name
  has_many :teams 
  accepts_nested_attributes_for :teams
end


class Team < ActiveRecord::Base
  has_many :users
  attr_accessible :name
end

这是我的控制器中的代码

def create
@users = User.all
@user = User.new
@teams = Team.all
@user.attributes = {:teams => []}.merge(params[:user] || {})
end

这是我的视图文件中的代码

<%= form_for @user, url: {action: "create"}  do |f| %>
<%= f.label :teams%>
<% for team in @teams %>
<%= check_box_tag team.name, team.name, false, :teams => team.name%>      
<%=  team.name -%>
<% end %>
<%= submit_tag "Create User" %>

我正在尝试将其展示到

<%= user.teams.name %>

但唯一的输出是“团队”有人能告诉我我做错了什么吗?

4

1 回答 1

1

实际上,你不能那样做一个多对多的关系......你需要这样做has_many :through或者 has_and_belongs_to_many在这里很好的解释......

http://guides.rubyonrails.org/association_basics.html

于 2013-06-26T01:23:59.317 回答