jor*_*dan 1 ruby activerecord ruby-on-rails ruby-on-rails-4
我有一个嵌套模型和对象.我目前正在获取所有嵌套对象:
@no = Parent.find(params[:parent_id]).children
Run Code Online (Sandbox Code Playgroud)
现在,其中一个孩子有一个属性,将其标识为收藏.如何从孩子中获得最喜欢的孩子?
此外,如何fields_for
在视图/更新中仅使用该单个对象编辑属性?
我不知道您的属性的名称将该记录标识为收藏,但让我们说它是一个boolean
名字is_favorite
.考虑到这种情况,以下情况应该有效:
children = Parent.find(params[:parent_id]).children
@favorited_children = children.where(is_favorite: true) # return 0..N records! not only 0..1 !
Run Code Online (Sandbox Code Playgroud)
要编辑其属性,您可以执行以下操作(您必须在ERB或HAML中进行翻译,具体取决于您的应用使用的内容):
form_for @favorited_children do |form_builder|
form_builder.text_field :name
form_builder.check_box :is_favorite
end
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!