0
# in the controller
def create
  @motivo_consulta = MotivoConsulta.new(params[:motivo_consulta])
  respond_to do |format|
  if @motivo_consulta.save
    format.html { redirect_to @motivo_consulta, notice: 'Motivo de consulta fue creado exitosamente.' }
    format.json { render json: @motivo_consulta, status: :created, location: @motivo_consulta }
  else
    format.html { render action: "new" }
    format.json { render json: @motivo_consulta.errors, status: :unprocessable_entity }
  end
end
4

4 回答 4

2

If you only need to set a default value for the field "estado" in "MotivoConsulta" model, try setting that value in one migration.

rails g migration SetDefaultValueToEstadoInMotivoConsulta

And in this migration set the default value of the estado field, as below:

class SetDefaultValueToEstadoInMotivoConsulta < ActiveRecord::Migration
  def up
    change_table :motivo_consulta do |t|
      t.string :estado, default: "Inactivo"
    end
  end
  def down
    change_table :motivo_de_mudanca do |t|
      t.string :estado
    end
  end
end

Also, you should proctect the attribute estado from mass-assignment in MotivoConsulta class:

class MotivoConsulta < ActiveRecord::Base
  #...
  attr_protected :estado
  #...
end

A different approach can be used by setting the default value in MotivoConsulta class, as described here.

There is something else that you might be interested in it's called the State Pattern and there are many gems available to help you with it.

于 2012-11-28T21:37:11.887 回答
2

你可以使用这样的东西:

@motivo_consulta = MotivoConsulta.new(params[:motivo_consulta].merge({:estado => 'inactivo'}))
于 2012-11-28T17:56:56.783 回答
2

首先,您应该重新考虑您的代码。你可以做这样的事情

respond_to :html, :json

def create
  @motivo_consulta = MotivoConsulta.new(params[:motivo_consulta].merge({:estado => 'inactivo'}))

  if @motivo_consulta.save
    respond_with(@motivo_consulta, notice: 'Motivo de consulta fue creado exitosamente.')
  else
    respond_with(@motivo_consulta.errors, status: unprocessable_entity)
  end
end

希望它能回答你的问题

于 2012-11-28T18:32:00.157 回答
1

我强烈建议您重构您的控制器,并将响应逻辑放入自定义响应器中。=p

关于您的问题,有一个可以帮助您的宝石:state_machine 这样您就可以在模型中使用您的业务逻辑,这是它应该在的地方。

于 2012-11-28T18:02:27.843 回答