accept nested attributes for has_many relationship

后端 未结 3 807
谎友^
谎友^ 2020-12-19 16:40

Below are my two model classes

class Patient < ActiveRecord::Base
  belongs_to :user, :dependent => :destroy
  has_many :enrollments, :dependent =>          


        
相关标签:
3条回答
  • 2020-12-19 16:46

    In Rails 3 (not sure about previous versions) you don't even need to use accepts_nested_attributes_for to accomplish this. You can simply remove all the view code you listed and replace it with the following:

    <%= patient_form.select(:client_ids, @clients.collect {|c| [ c.name, c.id ] }, {}, {:multiple => true})%>
    

    Rails will do its magic (because of you named the select "client_ids") and it will just work.

    0 讨论(0)
  • 2020-12-19 16:48

    I ended up doing the following:

    <%= check_box_tag "patient[client_ids][]", client.id, @patient.clients.include?(client) %>
    

    I am not sure if this is the best way...any comments (I had to update my model to include attr_accessible :client_ids

    0 讨论(0)
  • 2020-12-19 17:05

    Instead of

    :client_id
    

    in the collection_select, try

    "client_id[]"
    

    The second form specifies that you're accepting an array of IDs for the attribute rather than a single one.

    Here's a good resource on the usage of the select helpers in forms: http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails

    0 讨论(0)
提交回复
热议问题