0

I am making a model where users can belong to multiple teams and teams have multiple people. I have checkboxes but they don't pass the value onto the object.

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

Here is the code in my controller

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

Here is the code in my view file

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

I am trying to show it into

<%= user.teams.name %>

But the only output is "Team" Can someone tell me what I am doing wrong?

4
  • Are you reporting two problems (passing checkbox values and displaying team name)? user.teams refers to the whole collection of teams the user might belong to. So name isn't the name of a team, but might be picking up the name method of the class (which is Team). You need to show a specific team by selecting a team from user.teams (e.g., first_team = user.teams.first) then show its name (e.g., first_team.name). Commented Jun 25, 2013 at 1:31
  • @mbratch I didnt know checkbox sends a boolean. How can I get it to send the team name? team.name calls the team names. each team can have many names. Commented Jun 25, 2013 at 1:56
  • Sorry, I'm mistaken (got a little confused). You can use it to send a name, which is the value of the checkbox element. Did you try to do a view source (HTML) from your browser? See what that looks like. It can give a clue as to what's happening. Commented Jun 25, 2013 at 2:47
  • First, teams is ActiveRecord::Relation class, so you cannot call .name on it. Second, check_box_tag is currently not associated with the @user, so try using fields_for in the form. Commented Jun 25, 2013 at 10:58

1 Answer 1

1

Actually, you can't do a many-to-many relationship that way... you need to do has_many :through or alternatively has_and_belongs_to_many Nice explanation here...

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.