Question

I have and object with a nested model. I am currently getting all the nested objects like so:

@no = Parent.find(params[:parent_id]).children

Now, one of these children has an attribute that identifies them as the favorite. How can I get the favorite child from among the children?

In addition, how can I edit the attributes using fields_for for just that single object in the view/update?

Was it helpful?

Solution

I don't know the name of your attribute that identifies the record as the favorite, but let's say it is a boolean named is_favorite. Considering this abose, the following should work:

children = Parent.find(params[:parent_id]).children
@favorited_children = children.where(is_favorite: true) # return 0..N records! not only 0..1 !

To edit its attributes, you can do as following (you will have to translate it in ERB or HAML, depending on what your app uses):

form_for @favorited_children do |form_builder|
  form_builder.text_field :name
  form_builder.check_box :is_favorite
end 

Hope this helps!

OTHER TIPS

You could also look at using an ActiveRecord Association Extension

This basically works by creating instance methods you can chain onto the child association, like so:

#app/models/parent.rb
Class Parent < ActiveRecord::Base
    has_many :children do
       def favorites
           where(is_favorite: true) #-> to use MrYoshi's example
       end
    end
end

This will allow you to use the following:

@parent = Parent.find params[:id]
@favorites = @parent.children.favorites
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top