2012-02-01 65 views
0

所以只是一個簡單的描述。在'Users/Show'中,我有一個Clubs的表格,它接受CurrentClubs的嵌套屬性。我有一個俱樂部名稱的文本字段。如果輸入已存在的名稱,CurrentClubs的嵌套屬性將使用已創建的分會的ID創建記錄。如果俱樂部不存在,則創建俱樂部,然後將新俱樂部ID添加到CurrentClub嵌套屬性中的:club_id字段。find_or_initialize_by和嵌套屬性

問題並非試圖從新創建的俱樂部獲得id,它做得很好。問題是試圖從已經存在的俱樂部獲得id並將其放入嵌套屬性中。出於某種原因,它沒有被輸入到參數中。總之,如果我輸入一個不存在的新俱樂部,嵌套屬性將被完美輸入並且俱樂部被創建,如果俱樂部確實存在,它會捕獲除:club_id以外的嵌套屬性。

服務器不斷出現這樣的:提前

Processing by ClubsController#create as HTML 
    Parameters: {"club"=>{"name"=>"Pacha", "current_clubs_attributes"=>{"0"=>{"club_id"=>"", "user_id"=>"2"}}, "state"=>"1"}, "commit"=>"+", "authenticity_token"=>"OC4x6CxP3lfaSSneGRjiPDSm6ElxAbj2mGukOVD5VFc=", "utf8"=>"\342\234\223", "locale"=>"en"} 

Clubs#Controller 
    def create 
    @club = Club.find_or_initialize_by_name(params[:club][:name]) 
    @club.attributes = params[:club] unless @club.persisted? 
    respond_to do |format| 
     if @club.save 
     format.html { redirect_to(@club) } 
     else 
     format.html { redirect_to(clubs_url, :notice => 'club could not be created.') } 
     end 
    end 
    end 

Users#Controller 
     def show 
      @club = Club.new 
      1.times { @club.current_clubs.build } 
     end 

Club.rb 
class Club < ActiveRecord::Base 
attr_accessible :state_id, :country_id, :name, :rating, :club_promoters_attributes, :past_clubs_attributes, :current_clubs_attributes 
has_many :current_clubs 
has_many :past_clubs 
has_many :club_promoters 
belongs_to :state 

accepts_nested_attributes_for :club_promoters 
accepts_nested_attributes_for :past_clubs 
accepts_nested_attributes_for :current_clubs 

    scope :by_name, lambda { |s| 
    where("name LIKE ?", "#{s.strip}%") 
    } 


    def full_name 
    "#{name}" 
    end 

    default_scope :order => 'clubs.name ASC' 

end 

Current_clubs#form 
<div> 
<%= form_for(@club) do |f| %> 

    <input id="search_club" type="text" placeholder="Enter Club" /> 

    <%= f.hidden_field :name, :class => 'name' %> 
     <%= f.hidden_field :state, :value => @user.state_id %> 

     <%= f.fields_for :current_clubs do |current_clubs_fields| %> 
     <%= current_clubs_fields.hidden_field :club_id, :value => @club.id %> 

     <%= current_clubs_fields.hidden_field :user_id, :value => @user.id %> 

     <% end %> 




    <%= f.submit "+" %> 
<% end %> 

<script> 
    $("#search_club").bind('keyUp blur', function (event) { 
     var stt = $(this).val(); 
     $(this).parent().find(".name").val(stt); 
    }); 

</script> 

</div> 

謝謝,原諒我,如果我沒有使用過的事情的正確名稱,我不是一個偉大的開發者。使用rails 3.09和紅寶石1.87

回答

0

也許一些UsersController代碼丟失,但我看不到UsersController代碼所屬的操作。您是否嘗試將@club設置爲任何現有的記錄(例如@club = @user.clubs.first || Club.new)? @club = Club.new將始終返回一個空白標識...

+0

對不起,我現在編輯它。它在Show中。 – Dol 2012-02-01 01:42:11

+0

你想要整個UsersController嗎? – Dol 2012-02-01 01:42:54

+0

我試過@club = Club.first || Club.new,僅僅是因爲用戶沒有與俱樂部建立關係。這似乎是創造多個CurrentClubs ... – Dol 2012-02-01 01:52:23