Rails插入模型和关联..困惑

时间:2014-12-23 07:23:14

标签: ruby-on-rails ruby ruby-on-rails-4 model-associations

我很困惑为barangay个人资料写我的后端。在我的形式中有一个字段,要求输入你的barangay然后当它保存barangay字段将保存在barangay模型。在brgyprofile中它与barangay模型相关联,其中barangay模型的id是brgyprofile模型的FK。如何在barangay模型中保存数据。我已经尝试过它,但没有任何反应。 brgy_name没有保存在barangay模型中。我很困惑。我非常擅长使用rails并尝试创建应用程序。

的routes.rb

resources :brgyadmins do
    resources :brgyprofiles
  end

模型

class Brgyprofile < ActiveRecord::Base
    belongs_to :barangay
    belongs_to :brgyadmin
end

class Barangay < ActiveRecord::Base
    has_one :brgyprofile
end

_form.html.erb

<%= simple_form_for ([@brgyadmin,@new_profile]) do |f| %>
  <%= f.input :firstname, placeholder: 'Firstname' %>
  <%= f.input :lastname, placeholder: 'Lastname' %>
  <%= f.input :birthdate, :order => [:month, :day, :year] %>
  <%= f.input :gender,
    :as => :radio_buttons,
    :collection => %w[Female Male]
  %>
  <%= f.input :brgy_name, placeholder: 'Barangay' %>
  <%= f.input :brgy_position, placeholder: 'Barangay Position' %>
  <%= f.input :contact_number, placeholder: 'Contact Number' %>
  <%= f.button :submit, 'Submit' %>
<% end %> 

brgyprofile控制器

class BrgyprofilesController < ApplicationController
    before_action :set_brgyprofile, only: [:new, :create]

    def new
        @new_profile = @brgyadmin.build_brgyprofile
    end

    def create
        #respond_to do |format|
            if @brgyadmin.create_brgyprofile(profile_params) && Barangay.create(brgy_name: params[:brgy_name])
                logger.info "Saved!"
            else
                logger.info "Nothing happens"
            end
        #end
    end

    private

    def set_brgyprofile
        @brgyadmin = Brgyadmin.find(session[:user_id])
    end

    def profile_params
        params.require(:brgyprofile).permit(:firstname, :lastname, :birthdate, :gender, :brgy_position, :contact_number, :barangay_id, :brgy_name)
    end

end

0 个答案:

没有答案