Ruby on rails编辑has_one关系的表单

时间:2013-10-25 21:39:22

标签: ruby-on-rails activerecord

我有 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)

我建议你阅读导轨指南。开始时你会得到大部分答案。但这里是你问题的相关部分: http://guides.rubyonrails.org/getting_started.html#updating-posts