The best way is to book the ticket in advance, but buy the railcard when you arrive at the station.
However you really need to make sure you have the railcard before you ob-board the train, otherwise you may be considered as 'travel without a valid ticket'.