2012-03-01 9 views
1

現時点で私のゲームモデルのセクションを書く方法を解決しようとすると、問題が発生しました。モデル内に2つのifステートメントを記述する

私は現在、モデルの私のデフインデックスセクションで、次があります。

def index 
    games_relation = case params[:console].present? 
    when true then Game.where(:console => params[:console]) 
    else Game 
    end 
    @games = games_relation.search(params[:search]) 
end 

今正常に動作しますが、それは次のものが含まれて私は、ユーザー名を見て、別のセクションに追加する:

user_relation = case params[:username].present? 
    when true then User.where("username LIKE ?", "#{params[:username]}%") 
    else User 
end 

今私はインデックスに2つのループを入れていると思いますが、@games行をどうやってやりますか?

私は次のようなものを試してみましたが、運:それはgames_relationとuser_relationを呼び出すように

def index 
    games_relation = case params[:console].present? 
    when true then Game.where(:console => params[:console]) 
    else Game 
    end 

    name_relation = case params[:game_name].present? 
    when true then Game.where("game_name LIKE ?", "#{params[:game_name]}%") 
    else Game 
    end 

    @games = name_relation.games_relation.search(params[:search]) 
end 

私は現在、それがgames_relationを呼び出すが、どのようにしているが、私はそれを行うんでしょうか?

+1

申し訳ありませんが、私はあなたの問題を理解していないが、一つのこと、私は確実に伝えることができます:あなたが唯一の2つのオプションがあります場合は、case文を使用しないでください。代わりに 'if ... else'を使用してください。 –

+0

ちょっと私は、私が試したことと何をしようとしているのかを知るために質問を更新しました。 – user1222136

+0

ゲームとユーザーの関係を記述することができれば、2秒後にこれを引き上げます。 – TomDunning

答えて

2

belongs_to :user 

だから、あなたは、このようにそれを行うことができます

オプション1)これは最低限のコードの方法です:

@games = Game 
@games = @games.where("game_name LIKE ?", "#{params[:game_name]}%") if params[:game_name].present? 
@games = @games.where("console = ?", params[:console]) if params[:console].present? 

ただし、3つのクエリが発生します。

オプション2)1クエリ、より多くのコード:

@games = if params[:game_name].present? && params[:console].present? 
    Game.where("console = ? AND game_name LIKE ?", params[:console], "#{params[:game_name]}%") 
elsif params[:game_name].present? && !params[:console].present? 
    Game.where("game_name LIKE ?", "#{params[:game_name]}%") 
elsif !params[:game_name].present? && params[:console].present? 
    Game.where("console = ?", params[:console]) 
else 
    Game 
end 
+0

うん、それは私の質問に答えた。そのための乾杯:) – user1222136

0

KL-7アドバイスと同様に、if/elseを使用します。大文字小文字の目的は、複数のifがある場合です。あなたは1つか2つです。

複合検索を行う必要がある場合は、https://github.com/ernie/meta_searchを使用することをおすすめします。検索パラメータ(適切な名前のキー/値)を渡すだけで、あなたの世話をします。条件を

games_relation = params[:console].present? ? Game.where(:console => params[:console]) : Game 

そして

user_relation = params[:game_name].present? ? User.where("game_name LIKE ?", "#{params[:game_name]}%") : User 

ザッツ:あなたは、コードを読み取るためにハードになり、真または偽の条件のためのcase文を使用している

1

、あなたはこのような何かを行うことができます。しかし、私はあなたのモデルが、このようなものであることを、あなたのコードから推測:

ユーザー:

has_many :games 

ゲーム:

def index 
    @games = User.games 

    @games = @games.where(:console => params[:console]) if params[:console].present? 

    @games = @games.where("game_name LIKE ?", "#{params[:game_name]}%") if params[:game_name].present? 

    @games 
end 
+0

これは私の質問にも答えました。あなたの助けをありがとう:) – user1222136

関連する問題