Home > Mobile >  Rails 7 link_to show action without database connection
Rails 7 link_to show action without database connection

Time:09-19

In my Rails 7 app I've got Payments list from which the data comes from an external API, they are not stored in DB, like below:

  # payments_controller.rb

  def index
    @payments = client.payments(user_id: current_user.payment_platform_id)
  end

Which I display in the view:

# payments/index.html.erb
<table>
  <tbody>
    <% @payments.each do |payment| %>
      <tr>
        <td><%= payment.id %></td>
        <td><%= payment.amount %></td>
      </tr>
    <% end %>
  </tbody>
</table>

Now I want to add link_to which will redirect user to the show action of that particular payment - in simple words to the payments#show. Additionally, pass that payment to the params to be available as params[:payment] inside the controller show action. Like below:

# payments_controller.rb
def show
  @payment = params[:payment]
end

# payments/index.html.erb
<tbody>
  <% @payments.each do |payment| %>
    <tr>
      other stuff (...)
      <td>
        <%= link_to 'Details', payment_path(payment.id } %>
      </td>
    </tr>
  <% end %>
</tbody>

#routes.rb
resources :payments, only: %i[index show]

With this code redirects me to an empty index page. How to make this link_to works without storing payments in db ?

CodePudding user response:

By default in rails dynamic segment of the URL is :id but in show method you use @payment = params[:payment]

You can fix it 2 ways:

Try to catch params[:id]

def show
  @payment = params[:id]
end

Or another way: change dynamic segment name to :payment

resources :payments, only: %i[index show], param: :payment

In this case params[:payment] will be available

  • Related