2016-06-21 18 views
0

我无法使用accepts_nested_attributes_for保存子模型中的数据。 Althogh有很多类似的问题,他们不适合我。Rails4:accep_nested_attributes_for不保存数据在子模型和显示不允许的参数

保存数据时不显示错误消息。 但是Unpermitted parameter显示,INSERT为子模型不在日志中生成。

日志

INSERTamount不产生。

Unpermitted parameter: amount_attributes 
    (0.2ms) BEGIN 
    (0.2ms) BEGIN 
    SQL (3.8ms) INSERT INTO "events" ("start_at", "end_at", "title", "room_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["start_at", "2000-01-01 01:00:00.000000"], ["end_at", "2000-01-01 02:00:00.000000"], ["title", "add id parameter"], ["room_id", 38], ["created_at", "2016-06-21 07:31:05.143296"], ["updated_at", "2016-06-21 07:31:05.143296"]] 

模式

型号/ rooms.rb

has_many :events, inverse_of: :room, dependent: :destroy 
    has_many :amounts, inverse_of: :room, dependent: :destroy 
    accepts_nested_attributes_for :events, allow_destroy: true 

型号/ events.rb

has_one :amount, inverse_of: :schedule, dependent: :destroy 
    accepts_nested_attributes_for :amount, allow_destroy: true 

型号/ amounts.rb

belongs_to :room, inverse_of: :amounts 
    belongs_to :event, inverse_of: :amounts 

contrller

控制器/ events_controller.rb

before_action :load_room 

    def new 

    @event = Event.new 
    @event.room = @room 
    @event.build_amount 

    end 

    def create 

    @event = Event.new(event_params) 

    if @event.save 
     flash[:success] = "event created!" 
     redirect_to current_user 
    else 
     render 'new' 
    end 
    end 


    private 

    def load_room 
     @room = Room.find(params[:room_id]) 
    end 

    def event_params 
     params.require(:event).permit(
     :id, :_destroy, :start_at, :end_at, :title, :detail, :room_id, :category, :ccy, :amount, 
     amounts_attributes: [ 
      :id, :schedule_id, :room_id, :event_id, :ccy, :amount 
     ] 
     ) 
    end 

视图

/views/events/new.html.erb

<%= form_for([@room, @event]) do |f| %> 

    <%= f.label :title %> 
    <%= f.text_field :title %> 

    <%= f.text_field :start_at, :class => 'form-control'%> 
    <%= f.text_field :end_at, :class => 'form-control'%> 

    <%= f.fields_for :amount do |a| %> 
     <%= a.text_field :amount %> 
    <% end %> 

    <%= f.hidden_field :room_id %> 
    <%= f.submit "Post", class: "btn btn-primary" %> 

<% end %> 

这将是的欣赏如果你可以给我任何建议,

回答

1

不允许的参数:amount_attributes

根据您的关联,你需要在event_params方法来改变amounts_attributesamount_attributes

def event_params 
    params.require(:event).permit(:id, :_destroy, :start_at, :end_at, :title, :detail, :room_id, :category, :ccy, :amount, amount_attributes: [:id, :schedule_id, :room_id, :event_id, :ccy, :amount]) 
end 
+1

感谢您的快速响应,@Pavan。有用。我应该使用'has_one'的单数形式,'has_many'的复数形式。 – SamuraiBlue