How do i include Rails join table field in the for

2019-04-11 00:40发布

问题:

In this scenario I can insert values to the Member table and the Club table. But there is a field called :task in the memberships table that I want to submit a value to, and in the Memberships table member_id and club_id are inserted automatically by Rails. How do I include the task field in the form below? Thank you in advance.

View/form:

<%= form_for @member ,:url=>{:action =>"create"} do |f| %>
  <%= f.text_field :email %>
  <%= f.fields_for :clubs do |s| %>
    <%= s.text_field :name %>
  <% end %>
  <%= f.submit "submit" %>
<% end %>

Models

class Member < ActiveRecord::Base
  has_many :clubs ,:through=> :memberships
  has_many :memberships
  accepts_nested_attributes_for :clubs 
  attr_accessible :clubs_attributes
end

class Club < ActiveRecord::Base
  has_many :members ,:through=>:memberships
  has_many :memberships
end

class Memberships < ActiveRecord::Base
  belongs_to :Member
  belongs_to :Club
end

回答1:

<%= f.fields_for :memberships do |m| %>
  <%= m.text_field :task %>
  <%= m.fields_for :clubs do |s| %>
    <%= s.text_field :name %>
  <% end %>
<% end %>