Gugubaight
Gugubaight

Reputation: 187

Haml / Rails 4: Conditions - repeating code inside

How can I make something like this work with haml/rails:

- if current_user.is_seeking_job == true && current_user.is_seeking_contract == true
  - @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where("sort < ?", 2).limit(10).each do |job|
- else
  - @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where("sort > ?", 1).limit(10).each do |job|
    %li

Obviously I get an error because I have no code inside the first loop. The thing is that I have more than these two conditions and inside of %li is a lot of code.

Of course I could just copy it for each condition and it would work, but how can do that without copying the same piece of code over and over again?

Thanks in advance for any help!

Upvotes: 1

Views: 42

Answers (1)

pdoherty926
pdoherty926

Reputation: 10349

You could do something like the following:

- if current_user.is_seeking_job && current_user.is_seeking_contract
  - sort_order = "sort < ?"
  - sort_param = 2
- else
  - sort_order = "sort > ?"
  - sort_param = 1
- @jobsforyou.where.not(user_id: current_user, is_finished: true, is_active: false).where(sort_order, sort_param).limit(10).each do |job|

However, this solution is a violation of the separation of concerns principle - your view should (ideally) only be displaying data, not querying the database. I'd suggest moving the queries and associated logic somewhere more appropriate, like model methods or scopes.

Upvotes: 3

Related Questions