2015-09-13 2 views
0

У меня есть две модели: churchaddress и churchmember. Я спасаю членов церкви в своей собственной модели. Я хотел бы, чтобы несколько человек выбирали членов церкви через вложенные поля в форме_for churchaddress и сохраняли churchaddress_id на модели churchmember, когда я спасли церковь. В конце я хотел бы показать церковную молитву с членами церкви, где churchmembers.churchaddress_id = churchaddress_id.save childs_ids при сохранении parent_id - вложенный вид - collection_select (rails)

В данный момент у меня есть выбор коллекции во вложенном виде, но я не могу сохранить выбранных членов церкви (childs) в церковном адресе (родительском). Надеюсь, кто-то может мне помочь.

# churchaddress.rb model 
class Churchaddress < ActiveRecord::Base 
    has_many :churchmembers, dependent: :destroy, autosave: true 
    accepts_nested_attributes_for :churchmembers, 
            reject_if: proc { |attributes| attributes['name'].blank? }, 
            allow_destroy: true 
    validates_associated :churchmembers 
    validates :name, 
       presence: true 
    def to_s 
     name 
    end 
end 

# churchmember.rb model 
class Churchmember < ActiveRecord::Base 
    belongs_to :churchaddress 
    accepts_nested_attributes_for :churchaddress 
    validates :name, 
       presence: true 
    def to_s 
    name 
    end 
end 

# churchaddresses controller 
class ChurchaddressesController < ApplicationController 
    before_action :set_churchaddress, only: [:show, :edit, :update, :destroy] 

    def show 
    end 

    # GET /churchaddresses/new 
    def new 
    @churchaddress = Churchaddress.new 
    @churchaddress.churchmembers.build 
    end 

    # POST /churchaddresses 
    # POST /churchaddresses.json 
    def create 
    @churchaddress = Churchaddress.new(churchaddress_params) 

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

    private 
    def set_churchaddress 
     @churchaddress = Churchaddress.find(params[:id]) 
    end 

    def churchaddress_params 
     params.require(:churchaddress).permit(:name, churchmembers_attributes: [:id, :name, :_destroy, :churchmember_ids => [] ]) 
    end 
end 

# form_for with nested fields_for churchaddresses 

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

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

    <div class="field"> 
    <%= f.label :name %><br> 
    <%= f.text_field :name %> 
    </div> 

    <h2>Church members</h2> 
    <%= f.fields_for :churchmembers, @churchaddress.churchmembers do |churchmember| %> 
    <div class="churchmember_fields"> 
    <div class="field"> 

    <%= churchmember.collection_select(:churchmember_ids, Churchmember.all, :id, :name, {include_blank: false, :include_hidden => false, :selected => @churchaddress.churchmembers.map(&:id)}, {:multiple => true}) %> 

    </div> 
    </div> 
    <% end %> 
    <br> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

UPDATE 1: schema.rb

ActiveRecord::Schema.define(version: 20150909060826) do 

    create_table "churchaddresses", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "churchmembers", force: :cascade do |t| 
    t.string "name" 
    t.integer "churchaddress_id" 
    t.datetime "created_at",  null: false 
    t.datetime "updated_at",  null: false 
    end 

    add_index "churchmembers", ["churchaddress_id"], name: "index_churchmembers_on_churchaddress_id" 

end 

Заранее спасибо за ответы!

+0

Какое поле является 'churchmember_ids'? – vee

+0

@vee благодарит за ваш ответ. Я обновил свой вопрос с помощью schema.rb. Что касается churchmember_ids: я не указал это поле в своей базе данных. Не знаю, где я должен добавить это поле? ты можешь помочь мне с этим? –

ответ

0

Я, наконец, сумел решить эту проблему. Принял меня несколько ночей, но результат замечательный! Для людей с той же проблемой, я разместил измененные формы ниже.

class Churchaddress < ActiveRecord::Base 
    has_many :churchmembers, foreign_key: :churchaddress_id 
    accepts_nested_attributes_for :churchmembers 

    def to_s 
     name 
    end 
end 

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

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

    <div class="field"> 
    <%= f.label :name %><br> 
    <%= f.text_field :name %> 
    </div> 

    <h2>Church members</h2> 
    <div class="churchmember_fields"> 
    <div class="field">  
    <%= collection_select(:churchaddress, :churchmember_ids, Churchmember.all, :id, :name, {:selected => @churchaddress.churchmember_ids, :include_hidden => false}, {multiple: true}) %> 
    </div> 
    </div> 
    <br> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %>