创建模型对象时通过关联创建has_many

时间:2016-06-17 16:39:32

标签: ruby-on-rails simple-form has-many-through model-associations

我有两个型号;字母和代表,以及名为订阅的连接表。我的数据库中已经有很多代表。 我想在创建新信件时将一个或多个代表与一封信联系起来。我假设需要将某些内容添加到字母控制器以创建关联,但我不是要Rails和有点失落。提前谢谢!

letter.rb

class Letter < ActiveRecord::Base
  has_many :subscriptions
  has_many :representatives, :through => :subscriptions
  accepts_nested_attributes_for :subscriptions, 
      reject_if: :all_blank, 
      allow_destroy: true
end

representative.rb

class Representative < ActiveRecord::Base
    has_many :subscriptions
    has_many :letters, :through => :subscriptions
end

subscription.rb

class Subscription < ActiveRecord::Base
    belongs_to :letter
    belongs_to :representative
end

订阅迁移

class CreateSubscriptions < ActiveRecord::Migration
  def change
    create_table :subscriptions do |t|
      t.integer :letter_id
      t.interger :representative_id
      t.belongs_to :letter, index: true
      t.belongs_to :representative, index: true

      t.timestamps null: false
    end
  end
end

letter _form.html.erb

<%= simple_form_for @letter do |f| %>
  <% if @letter.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@letter.errors.count, "error") %> prohibited this letter from being saved:</h2>

      <ul>
      <% @letter.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :subject %><br>
    <%= f.text_field :subject %>
  </div>
  <div class="field">
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>
  <div class="field">
    <%= f.label 'Recipients'%><br>
    <%= f.association :representatives, as: :check_boxes,label_method: :first_name  %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

letters_controller.rb

def new
    @letter = Letter.new
end

def create
    @letter = Letter.new(letter_params)

    respond_to do |format|
    if @letter.save
        format.html { redirect_to @letter, notice: 'Letter was successfully created.' }
        format.json { render :show, status: :created, location: @letter }
    else
        format.html { render :new }
        format.json { render json: @letter.errors, status: :unprocessable_entity }
    end
  end
end

0 个答案:

没有答案