Zakoff
Zakoff

Reputation: 13005

rails - confused about routing and params

I have a two models, Group and User

User belongs_to Group and Group has_many Users

In my groups/show.html.erb I have the user sign-up form

<h1>Create user</h1>

<%= form_for @user do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :password_confirmation, "Confirmation" %><br />
    <%= f.password_field :password_confirmation %>
  </div>
  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>    

To get a relation between the Group and the User I have a create method in my Users controller as follows

def create
    @group = Group.find(params[:group][:id])    
    @user = @group.users.build(params[:user])
    if @user.save
      flash[:success] = "You have created a new user"
      redirect_to group_path
    else
      @title = "Create user"
      render 'new'
    end
end

I have also tried: @group = Group.find(params[:id])

and

@group = Group.find(params[:group_id])

But I still get an error

Essentially I want to create new users in the group/show.html.erb and associate that user with the group where the user was created. If the user is created in groups/3 for example, how do I set my create method in the Users controller to make sure this relation holds?

In general I've been following the Hartl Rails tutorial book at http://ruby.railstutorial.org/chapters/user-microposts#sec:creating_microposts and following the approach for forms and create methods. However I am not sure how to get the params for groups/3 into the find method like @group = Group.find(?????)

Can someone please enlighten me, this issue has been bothering me for a few days now.

Thanks in advance

Upvotes: 0

Views: 104

Answers (1)

bassneck
bassneck

Reputation: 4043

After the form is submitted, it takes you to the users#create. This route doesn't have a group_id segment.

To pass group_id there, you need to store it in a hidden field in your form.

Upvotes: 1

Related Questions