over 3 years ago

最重要參考:Rails 3: Multiple Select with has_many through associations

參考1.:document 在這


參考3.:Building a has_many, through model relationship and form with Cocoon

參考4.:Deep Nested Attributes Using Has_many Through Join Model

參考5.:accepts_nested_attributes_for with Has-Many-Through Relations
參考5重點節錄:The inverse_of option allows you to tell Rails when two model relations describe the same relationship, but from opposite directions. For example, if a User has_many :posts and a Post belongs_to :user, you can tell Rails that the :user relation on Post is the inverse of the :posts relation on User.

參考6.:Complex Rails Forms with Nested Attributes
參考6重點節錄:Please note the changed variable name for the fields_for block—ff rather than f. In this case for a has_one relationship, the logic is “if an address exists, show a field to edit the city attribute. Otherwise if there is no address, don’t show any fields.” Here we hit our first stumbling block: if the fields are hidden when there is no address, how do we create an address record in the first place? Since this is a view problem (do we display fields or not?), we want to solve this problem in the view layer. We do this by setting up default values for the form objectin a helper:

module FormHelper
def setup_user(user)
user.address ||= Address.new
<%= form_for(setup_user(user)) do |f| %>
← 配對的問題 後台:Cate, Issue, Option的建置 (Active Record Associations) →