mercredi 26 avril 2017

Ruby on Rails update method is accidentally called.. why?

I'm still new to Ruby on Rails and I am stucking at one Point.

My Database contains a Teacher and a Course model. They are associated with a has_and_belongs_to_many Association (at the moment it shouldn't be changed).

Course Detail View:

<p> Teacher:
    <%= form_tag url_for(controller: 'courses', action: 'add_teacher') ,method: 'put' do%>
    <%= select_tag :teacher, options_for_select(Teacher.all.collect {|t| [t._name, t.id]})%>
    <%= hidden_field_tag(:course, value = @course.id) %>
    <%= submit_tag 'hinzufügen' %>
    <%end %>
<% end %></p>

Course_Controller:

def add_teacher
    @course = Course.find(params[:course])
    @teacher = Teacher.find(params[:teacher]) unless params[:teacher].nil?
    @course.teachers << @teacher
    redirect_to action: 'show'
end


def update
    redirect_to action: 'add_teacher', course: params[:course], teacher: params[:teacher]
end

That was a part of my code. I don't really know if there is a routing problem or something else. I just don't get the point why the function update is called before the function add_teacher is called. First I thought maybe rails realized that I would like to change a existing record, so the function "update" is called when the change (@course.teachers << @teacher) "is happening" . But he first calls the update function and it doesn't matter if I redirect to add_teacher or not, he would call the function anyway! why?

Now i'm using the update function to redirect to add_teacher with the correct params. May someone has a better solution for me or an answer why the function 'update' is called automatically and how to set the routes correctly?

Thanks a lot for help and sorry for my bad english!

Bye

Aucun commentaire:

Enregistrer un commentaire