Routes calling the same controller action

Asked

Viewed 543 times

0

Hello, I have the following problem:

I am creating a film rental system at a college job where the user can rent movies from different rental companies.

The first problem I’m having with routes, is that a user can add movies to favorites, so I tried to create the route this way:

  resources :usuarios do
    resources :filmes
  end

that generated the routes:

    usuario_filmes GET    /usuarios/:usuario_id/filmes(.:format)      filmes#index
           POST   /usuarios/:usuario_id/filmes(.:format)      filmes#create
new_usuario_filme  GET    /usuarios/:usuario_id/filmes/new(.:format)  filmes#new
edit_usuario_filme GET    /usuarios/:usuario_id/filmes/:id/edit(.:format)      filmes#edit
    usuario_filme  GET    /usuarios/:usuario_id/filmes/:id(.:format)  filmes#show
           PATCH  /usuarios/:usuario_id/filmes/:id(.:format)  filmes#update
           PUT    /usuarios/:usuario_id/filmes/:id(.:format)  filmes#update
               DELETE /usuarios/:usuario_id/filmes/:id(.:format)  filmes#destroy

The problem is that these routes are calling the same actions that I use to create a new movie. My question is how to specify the actions to be called within the controller.

Another problem I’m having is with the table preco which refers to the lease value and the key of that table is composed of: locadora_id and filme_id. How do I create routes to register a new price? I’m trying it this way:

  match 'precos/new/:filme_id', controller: 'precos', action: 'new', via: 'get'

Where, in the view, the user informs the location id. But this route always calls the show method and understands that the new is the locator_id parameter, because the show method is defined like this:

precos/:locadora_id/:filme_id

I would love to be helped to better understand how the routes in Rails work.

The models:

class Preco < ApplicationRecord
    belongs_to :filme
    belongs_to :locadora
end

class Filme < ApplicationRecord
    has_and_belongs_to_many :usuarios
    has_many :precos, dependent: :destroy
end

class Locadora < ApplicationRecord
    has_and_belongs_to_many :usuarios
    has_many :precos, dependent: :destroy
end

1 answer

0

I believe your problem lies in the relationship. You need to create a controller and Resources for an associative table.

Example:

class Favoritos < ApplicationRecord
  has_many :usuaio
  has_many :filme
end

If you want you can create it through a scaffold.

This relationship is necessary to process information through routes. Because they usually only insert into a table.

Already the question of price can be solved with the resource. Regardless of whether or not you agree, just do the selects in view, or if you like, you can use the accepts_nested_attributes_for in the model and register more than one table using this line.

Particular example:

STUDENT MODEL

class Aluno < ApplicationRecord
  belongs_to :pessoa, dependent: :destroy
  accepts_nested_attributes_for :pessoa
end

    ##CONTROLLER aluno
    
        class AlunosController < ApplicationController
          before_action :set_aluno, only: [:show, :edit, :update, :destroy]
        
          # GET /alunos
          # GET /alunos.json
          def index
            @alunos = Aluno.all
          end
        
          # GET /alunos/1
          # GET /alunos/1.json
          def show
          end
        
          # GET /alunos/new
          def new
            @aluno = Aluno.new
            @aluno.build_pessoa
          end
        
          # GET /alunos/1/edit
          def edit
          end
        
          # POST /alunos
          # POST /alunos.json
          def create
            @aluno = Aluno.new(aluno_params)
            respond_to do |format|
              if @aluno.save
                format.html { redirect_to @aluno, notice: 'Aluno was successfully created.' }
                format.json { render :show, status: :created, location: @aluno }
              else
                format.html { render :new }
                format.json { render json: @aluno.errors, status: :unprocessable_entity }
              end
            end
          end
        
          # PATCH/PUT /alunos/1
          # PATCH/PUT /alunos/1.json
          def update
            respond_to do |format|
              if @aluno.update(aluno_params)
                format.html { redirect_to @aluno, notice: 'Aluno was successfully updated.' }
                format.json { render :show, status: :ok, location: @aluno }
              else
                format.html { render :edit }
                format.json { render json: @aluno.errors, status: :unprocessable_entity }
              end
            end
          end
        
          # DELETE /alunos/1
          # DELETE /alunos/1.json
          def destroy
            @aluno.destroy
            respond_to do |format|
              format.html { redirect_to alunos_url, notice: 'Aluno was successfully destroyed.' }
              format.json { head :no_content }
            end
          end
        
          private
            # Use callbacks to share common setup or constraints between actions.
            def set_aluno
              @aluno = Aluno.find(params[:id])
            end
        
            # Never trust parameters from the scary internet, only allow the white list through.
            def aluno_params
              params.require(:aluno).permit(:pessoa_id, :ativo, :matricula, pessoa_attributes: [:nome, :rua, :bairro, :sexo, :telefone, :email])
            end
        end

    #VIEW _form aluno
    <%= form_with(model: aluno, local: true) do |form| %>
      <% if aluno.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(aluno.errors.count, "error") %> prohibited this aluno from being saved:</h2>
    
          <ul>
          <% aluno.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
          </ul>
        </div>
      <% end %>

<%= form.fields_for :pessoa do |form| %>
<div class="container">
  <div class="formulario">
  <div class="field">
    <%= form.label "Nome:" %> 
    <br><%= form.text_field :nome, id: :pessoa_nome, :placeholder => "Nome Completo", :size => "60" %>
  </div>
  
  <div class="field">
    <%= form.label "Rua: " %>
    <br><%= form.text_field :rua, id: :pessoa_rua, :size => "60" %>
  </div>

   <div class="field">
    <%= form.label "Bairro: " %>
    <br><%= form.text_field :bairro, id: :pessoa_bairro, :size => "60"%>
  </div>

  <div class="field">
    <%= form.label "Sexo: " %>
    <br><%= form.select :sexo, ['Masculino', 'Feminino'] %><br>
  </div>

  <div class="field">
    <%= form.label "Telefone: " %>
    <br><%= form.number_field :telefone, id: :pessoa_telefone, :size => "60"%>
  </div>

  <div class="field">
    <%= form.label "Email: " %>
    <br><%= form.text_field :email, id: :pessoa_email, :size => "60"%>
  </div>
<% end %>

  <div class="field">
    <%= form.label "Ativo: " %>
    <br><%= form.check_box :ativo, id: :aluno_ativo %>
  </div>

  <div class="field">
    <%= form.label "Matrícula" %>
    <br><%= form.text_field :matricula, id: :aluno_matricula, :size => "60"%>
  </div>
</div>  
</div>
  <div class="actions">
    <%= link_to ' << Voltar', alunos_path, :class => "btn btn-danger text-white" %>
    <button type="submit" class="btn btn-success">Salvar Aluno</button>
  </div>
<% end %>

Using this I managed to register a person and at the same time store the ID of that person in the student, would be a kind of form_f.

  • I edited your answer, removing your email, if the author of the question has more questions, you should resolve them here or open a new question. Remember that his doubt may be of others so it is better for the community that the solution is always visible.

  • Obg Caique! I’ll remember that later...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.