Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Form with belongs_to Association

I'm very new to Rails so this may be an obvious problem, and if so I apologize.

I am trying to create a form for creating a User record, which has a belongs_to association with a Team model. What I've done so far is the following...

<% form_for @user, url: {action: "create"} do |f| %>
  <%= f.text_field :name %>
  <%= f.text_field :email %>

  <% f.fields_for :team do |team| %>
    <%= team.collection_select(:team_id, Team.all, :id, :name) %>
  <% end %>
  <%= f.submit %>
<% end %>

This seems to work well enough, but when creating the User record I'm running into trouble.

def create
  @team = Team.find(params[:user][:team][:team_id])
  @team.users.create(user_params)
  # Ignoring error checking for brevity
end

def user_params
    params.require(:user).permit(:name, :email)
end

The params now contains a field for team_id which is not an attribute of the User model, and thus the creation fails. I'm not sure how to go about addressing that, let alone whether or not this is the appropriate way to approach this. Any advice would be greatly appreciated!

like image 492
Alex P Avatar asked Dec 05 '22 20:12

Alex P


1 Answers

welcome to Rails :)

There is no problem with your logic of going about the association this way if the goal is to make sure that each user can be part of a team.

So first you'll need to make sure that team_id exists on the user model. And seoncdly, as Doon suggested, you don't need fields_for unless you want to interact with the team model and make changes from within that same form.

So first create a migration rails g migration add_team_to_user team:belongs_to

using belongs_to in your migration will add a reference, which you can learn about here: http://edgeguides.rubyonrails.org/active_record_migrations.html

Then migrate your database bundle exec rake db:migrate

and restart your server. Then change your form like so:

<% form_for @user, url: {action: "create"} do |f| %>
  <%= f.text_field :name %>
  <%= f.text_field :email %>
  <%= f.collection_select(:team_id, Team.all, :id, :name) %>

  <%= f.submit %>
<% end %>
like image 126
trh Avatar answered Dec 23 '22 20:12

trh