开发者

Rails: How to manipulate find(params[])

开发者 https://www.devze.com 2023-03-08 13:37 出处:网络
I am trying to use Object.find(params[]) to only return objects with :stage_id = integer Here is my controller code

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 uni开发者_开发技巧ts that have the indicated table values?


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


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]])


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
0

精彩评论

暂无评论...
验证码 换一张
取 消