Adding a user's ID to a teacher from a form in rails -


i have following table in html having student select teacher

<table>   <thead>     <tr>       <th>name</th>       <th>email</th>       <th>phone</th>       <th></th>     </tr>   </thead>   <tbody>     <% @teachers.each |teacher| %>       <tr>         <td><%= teacher.name %> </td>         <td><%= teacher.email %> </td>         <td><%= teacher.phone %> </td>         <%= form_for teacher |f| %>           <td><%= f.submit yield(:button_text), class: "btn btn-primary" %></td>           <%= f.hidden_field :user_id, value: @user.id %>         <% end %>       </tr>     <% end %>   </tbody> </table> 

but when click "select" button (which yielded :button_text), doesn't assign student teacher. controller code update action within teachers_controller

def update   @teacher = teacher.find(params[:id])   if params[:user_id]     @user = user.find(params[:user_id])     if @teacher.users << @user       flash[:success] = "profile updated"       redirect_to @user     else       render 'select'     end   else     if @teacher.update_attributes(teacher_params)       flash[:success] = "teacher updated"       redirect_to @teacher     else       render 'edit'     end   end end 

i'm trying make if hidden_field of user's id present attribute of teacher updated students, otherwise attributes (shown in table) updated. doing wrong?

what doing wrong?

you'll not passing params[:user_id] form; params[:teacher][:user_id]

def update    @teacher = teacher.find(params[:id])    if params[:teacher][:user_id]      @user = user.find params[:teacher][:user_id]      if @teacher.users << @user 

--

you'll better putting functionality separate method, not butcher update action:

#config/routes.rb resources :teachers     match :users, via: [:patch, :delete] #-> url.com/teachers/:teacher_id/users end  #app/views/teachers/index.html.erb <% @teachers.each |teacher| %>     <%= button_to "add", teacher_users_path(teacher), method: :patch, params: { user_id: @user.id } %> <% end %>  #app/controllers/teachers_controller.rb class teacherscontroller < applicationcontroller     def users        @teacher = teacher.find params[:teacher_id]        if params[:user_id]           @user = user.find params[:user_id]           @teacher.users << @user     if request.patch?           @teacher.users.delete @user if request.delete?        end        redirect_to teachers_path     end end 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -