You will need to use the "initialize" method in the StationForm object to use it for editing. if you pass id, it will assume that the object already exists, and from there we can consider it as an object with conservation. Also add the "update" method to update the attributes of the object.
class StationForm include Virtus.model include ActiveModel::Model
And the controller will be like
def new @station = StationForm.new end def edit @station = StationForm.new("id" => params[:id]) end def create @station = StationForm.new(station_params) respond_to do |format| if @station.save format.html { redirect_to stations_path, notice: 'Station was successfully created.' } format.json { render :show, status: :created, location: @station } else format.html { render :new } format.json { render json: @station.errors, status: :unprocessable_entity } end end end def update @station = StationForm.new(station_params.merge("id" => params[:id])) respond_to do |format| if @station.update format.html { redirect_to stations_path, notice: 'Station was successfully updated.' } format.json { render :show, status: :ok, location: @station } else format.html { render :edit } format.json { render json: @station.errors, status: :unprocessable_entity } end end end
use the "persisted" and "id" method from StationForm in the _form.html.erb file
<%= form_for(@station, :url => @station.persisted? ? station_path(@station.id) : stations_path, :method => @station.persisted? ? "put": "post") do |f| %> <% if @station.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@station.errors.count, "error") %> prohibited this station from being saved:</h2> <ul> <% @station.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :station_name %><br> <%= f.text_field :station_name %> </div> <div class="field"> <%= f.label :station_description %><br> <%= f.text_field :station_description %> </div> <div class="field"> <%= f.label :address_url%><br> <%= f.text_field :address_url %> </div> <div class="field"> <%= f.label :address_priority%><br> <%= f.text_field :address_priority%> </div> <div class="field"> <%= f.label :address_is_active %><br> <%= f.text_field :address_is_active %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
source share