问题描述:

In my app users can store private trades in their accounts, such trades are visible only to them.

The Trade model looks like this:

class Trade < ActiveRecord::Base

scope :by_user, lambda { |user|

where(user_id: user.id) unless user.nil?

}

belongs_to :status

belongs_to :user

the route looks like this:

resources :users do

resources :trades

end

so generating urls like:

/users/:user_id/trades/:id/edit

Currently for example, if there are three trades stored in the system, a new user, when creating his first trade would be creating a trade with id = 4, and his URL to find it would be: /users/2/trades/4

I would like to have the trades to have a new sequence_number column and this to be used in the id to find the trades.

So every user will see only his/her trades, and they will be all numbered starting from 1.

网友答案:

To change the parameter passed for a route, first change in your controller how you find a trade given an :id for that trade parameter.

class TradeController < ApplicationController
  before_action :find_trade, only [:edit, :show, :update, :destroy]
  # Remove @trade = Trade.find(params[:id]) from those four actions

  private
    def find_trade
      @user = User.find params[:user_id]
      @trade = @user.trades.find_by sequence_number: params[:id]
    end
end

Then, in your Trade model, make sequence_number your new parameter.

class Trade < ActiveRecord::Base
  def to_param
    sequence_number
  end
end

The to_param method of a model changes the parameter passed in routes for trades/:id from id to sequence_number. So, in your example above for a new user, showing their first trade will be /users/2/trades/1 rather than /users/2/trades/4.

相关阅读:
Top