Ruby on rails在嵌套表单上遇到麻烦

时间:2013-10-26 18:00:40

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

我有 clan.rb clan_options.rb

clan.rb

class Clan < ActiveRecord::Base
    has_one :options, :class_name => "ClanOptions", :foreign_key => "clan_id", dependent: :destroy
    accepts_nested_attributes_for :options
end

clan_options.rb

class ClanOptions < ActiveRecord::Base
  belongs_to :clan
end

要为 clan.rb clan_options.rb 创建编辑表单,请在 edit.html.erb 中使用以下内容:

<%= form_for @clan, :html => {:class => 'form-horizontal'} do |clan| %>
    <fieldset>
        <!-- Form stuff -->
        <%= clan.fields_for :options do |o| %>
            <!-- o.text_field -->
        <% end %>
    </fieldset>
<% end %>

我可以更新 clan.rb 的字段,但是当我尝试编辑值backgroundurl时,它不会保存它。 Backgroundurl是 clan_options.rb

之一

clans_controller.rb

class ClansController < ApplicationController
    before_filter :check_login, :only => [:new, :edit]
    before_filter :check_bound, :only => [:new, :edit]
    before_filter :check_clan, :only => :new

    def update
        @clan = Clan.find(params[:id])
        if @clan.update_attributes(clan_update_params)
            flash[:status] = TRUE
            flash[:alert] = "Successfully updated your clan."
            redirect_to clan_path(params[:id])
        else
            flash[:status] = FALSE
            flash[:alert] = @clan.errors.full_messages

            redirect_to edit_clan_path(@clan.id)
        end
    end

    def edit
        clan = Clan.where(id: params[:id])
        if !clan.blank?
            @clan = Clan.find(params[:id])

            user = User.where(id: session[:user_id])
            if !user.blank?
                #De gebruiker is ingelogt en zit in de clan
                @user = User.find(session[:user_id])
                if @clan.id != @user.clan.id
                    flash[:status] = FALSE
                    flash[:alert] = 'That was not your clan, you may not edit theirs.'
                    redirect_to clans_path
                elsif @user.clanmember.group.rank != 10
                    flash[:status] = FALSE
                    flash[:alert] = "You must be the leader to edit the clan."
                    redirect_to clan_path(@clan.id)
                end
            end
        else
            flash[:status] = FALSE
            flash[:alert] = 'that clan doesn\'t exist or has been removed.'
            redirect_to clans_path
        end
    end

    def clan_params
        params.require(:clan).permit(:name, :prefix, :description, :user_id)
    end

    def clan_update_params
        params.require(:clan).permit(:name, :prefix, :description, :user_id, options: [:id, :clan_id, :backgroundurl])
    end
end

1 个答案:

答案 0 :(得分:0)

我通过更改

修复了它
def clan_update_params
    params.require(:clan).permit(:name, :prefix, :description, :user_id, options: [:id, :clan_id, :backgroundurl])
end

def clan_update_params
    params.require(:clan).permit(:name, :prefix, :description, :user_id, options_attributes: [:backgroundurl])
end