編輯表單我有一個clan.rb和clan_options.rbRuby on Rails的爲HAS_ONE關係
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
要創建一個
<%= 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的領域,但是當我嘗試:爲clan.rb和clan_options.rb我用下面的edit.html.erb編輯表單編輯值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
您可以使用相同的表單。只需創建一個名爲'clans/edit.html.erb'的新文件,並在此文件中放置相同的表單 – fontno
我認爲您正在尋找嵌套表單請參閱[this](http://railscasts.com/episodes/196-nested -model-form-part-1) – tihom