Rails forms for has_many through association with additional attributes?

后端 未结 3 1996
轮回少年
轮回少年 2020-12-08 06:07

How can I generate form fields for a has_many :through association that has additional attributes?

The has_many :through relationship has a

3条回答
  •  死守一世寂寞
    2020-12-08 06:35

    Thanks a lot for the cocoon pointer nathanvda. I have been scratching my head about some problems I had when trying to implement this under rails 4.0.0-rc1 and I thought I would share my findings just in case someone has the same problems when attempting this udner rails4.

    Using the above code as an example, I did add user_id and widget_id to the permitted parameters as they are saved in the connecting table user_widgets. In rails 3 you did have to add them to attr_accesible in the user model but in rails 4 you have to add them to the allowed parameters in the controller of the main model you use for nesting, so here that would be the users_controller:

    params.require(:user).permit(...user_fields...,  
      user_widgets_attributes: [:user_id, :widget_id])
    

    Doing only this you end up with several of problems:

    1. Every association (widget) gets multiplied when updating a user record. 1 becomes 2, 4, 8, and so on, when updating and saving the record.
    2. removing an association does not work, the field is removed from the form but the association remains in the DB.

    To fix these problems you also need to add :id and :_destroy to the list of permitted attributes:

    params.require(:user).permit(...user_fields...,  
      user_widgets_attributes: [:user_id, :widget_id, :id, :_destroy])
    

    after that it works flawlessly.

    Juergen

    PS: For now you have to use the git repository in your Gemfile to use cocoon under rails 4 until a rails 4 compatible gem is released. Thanks for the email nathanvda on my bug report!!

提交回复
热议问题