ActiveRecord范围"默认"结果

时间:2015-09-28 20:49:32

标签: ruby-on-rails ruby-on-rails-4

所以,让我说我想在ActiveRecord范围内检查nils:

public class CommandService : ICommandService
{
    private readonly IEnumerable<ICommandHandler> _commandHandlers; 
    private readonly ISerializationFormatter _formatter;

    public CommandService(IEnumerable<ICommandHandler> commandHandlers,
        ISerializationFormatter formatter)
    {
        _commandHandlers = commandHandlers;
        _formatter = formatter;
    }

    public void Execute(string command)
    {
        if (command == null)
            throw new ArgumentNullException("command");

        var request = _formatter.Deserialize<CommandRequest>(command);

        var handler = _commandHandlers
            .Single(x => x.CommandType == request.Command.GetType());

        handler.Handle(request.Command);
    }
}

private void ConfigureContainer(Container container)
{
    container.Register(typeof(ICommandHandler<>),new[] { typeof(BusinessLayer).Assembly });

    container.RegisterDecorator(typeof(ICommandHandler<>),
        typeof(WeaklyTypedCommandHandler<>));

    //container.RegisterCollection<ICommandHandler>????
}

3 个答案:

答案 0 :(得分:2)

您可以返回self来返回默认范围:

class Person < ActiveRecord::Base

  def self.closest(point = nil)
    point.nil? ? self : where(point: point)
  end

end

答案 1 :(得分:2)

修改/溶液

正如上面的评论所述,正如@ahmacleod指出的那样,all正是我们正在寻找的

scope :closest, ->(point) {
  point.nil? ? all : where(point: point)
}

结束修改

我想我找到了我要找的东西,它是unscoped

scope :closest, ->(point) {
  point.nil? ? unscoped : where(point: point)
}

问题在于,如果我将其链接起来,如果我在它们之后使用它,我将失去先前的范围。

答案 2 :(得分:0)

您可以将point参数设置为可选。像这样:

scope :closest, -> (point = '') {
  where(point: point)     
} 

这样,范围每次都会返回一个ActiveRecord :: Relation。

希望这有帮助:)