yoshyosh
yoshyosh

Reputation: 14086

Rails: How to manipulate find(params[])

I am trying to use Object.find(params[]) to only return objects with :stage_id = integer

Here is my controller code

def show
    @lesson = Lesson.find(params[:id])
    @stage1 = @lesson.units(params[:stage_id] == 1)
    @stage2 = @lesson.units(params[:stage_id] == 2)

Each lesson has many units, each unit has either a stage_id = 1 or stage_id = 2, I want @stage1 to become an array with units that only have a stage_id value of 1. The same goes for stage2.

How can I properly use params to return only units that have the indicated table values?

Upvotes: 0

Views: 1697

Answers (3)

DonaldSowell
DonaldSowell

Reputation: 396

If Units are "always' going to be structured with Stages, one thing you could do to DRY up your code is to have a Stage model. That allows flexibility to add more stages in the future without breaking code. Assuming that relationship is properly established and data is good, you could do something like the following.

controller code

@lesson = Lesson.find(params[:id])

view code (haml)

- for stage in @lesson.stages
  = stage.name
  - for unit in stage.units
    = unit.name

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 186984

def show
  @lesson = Lesson.find(params[:id])
  @stage1 = @lesson.units.first(:conditions => { :stage_id => 1 })
  @stage2 = @lesson.units.first(:conditions => { :stage_id => 2 })
end

Upvotes: 2

Salil
Salil

Reputation: 47472

Ref find

@stage1 = Unit.find(:all, :conditions => ["stage_id=? AND lession_id=?" 1, params[:id]])


@stage2 = Unit.find(:all, :conditions => ["stage_id=? AND lession_id=?" 2, params[:id]])

Upvotes: 0

Related Questions