2014-01-05 28 views
2

我正在使用rails 4.0.2和globalize 4.0.0.alpha.3,但我無法用強參數列表將數據寫入翻譯數據庫。全球化的Gem和Rails 4強大的參數

我有一個報價模型和關注(OfferTranslationConcern)

class Offer < ActiveRecord::Base 
     include OfferTranslationConcern 
    end 

的關注

module OfferTranslationConcern 
     extend ActiveSupport::Concern 

     included do 
     attr_accessor :attribute_translations 

     translates :name, :city, :includes, :notes, :description, :slug 
     end 
    end 

控制器

def update 
     respond_to do |format| 
     if @offer.update(offer_params) 
      format.html { redirect_to @offer, notice: 'Offer was successfully updated.' } 
      format.json { head :no_content } 
     else 
      format.html { render action: 'edit' } 
      format.json { render json: @offer.errors, status: :unprocessable_entity } 
     end 
     end 
    end  

而強大的參數定義

params.require(:user).permit('a lot of offer parameters', :attribute_translations => [:id, :name, :city, :includes, :notes, :description, :slug] 
    ) 

對於我正在使用的翻譯,例如西班牙語和意大利語(it和es)。當我更新了報價,我得到不允許的參數:它,ES

的參數如下:

"offer"=>{"attribute_translations"=>{"it"=>{"name"=>"dsfdsf", "city"=>"sdf", "includes"=>"sdfsdf", "notes"=>"sdfsd", "description"=>"fsdf"}, "es"=>{"name"=>"", "city"=>"", "includes"=>"", "notes"=>"", "description"=>""}}, "provider_id"=>"1",...a bunch of other stuff 

現在我做到了這一定義的強大的參數工作

def offer_params 
     params.require(:offer).permit! 
    end 

這項工作,但我不認爲這是最好的方法。所以,我的問題是如果有一種方法來定義參數列表並使其工作?

回答

1

您聲明這一點:

:attribute_translations => [:id, :name, :city, :includes, :notes, :description, :slug] 

但你收到此:

"attribute_translations"=>{"it"=>{"name"=>"dsfdsf", "city"=>"sdf", "includes"=>"sdfsdf", "notes"=>"sdfsd", "description"=>"fsdf"} 

如果:id => "it",那麼你需要聲明它是這樣的:

:attribute_translations => [:id => [:name, :city, :includes, :notes, :description, :slug]] 

至少,是你的表單認爲你想要的格式。因此,您需要將表單的格式與您的表單中的參數或參數相匹配。

permit!方法並不是您所說的最佳選擇,它非常不安全,因爲它將白名單傳遞給它。如果您需要提交未知數量的參數,則必須使用相當複雜的塊。如果是這樣,請閱讀:Unpermitted parameters for Dynamic Forms in Rails 4

+0

Thx爲答案。 –

1

通過globalize-accessors避免這種痛苦寶石。 attr-accessor被棄用,gem直接解決這個問題。模型需要一個班輪我們的翻譯列聲明之後

globalize_accessors :locales => [:it, :en, :fr, :es, :de, :gr], :attributes => [:name] 

控制器也是一個班輪(如果所有字段都翻譯),二如果你混搭

params.require(:channel).permit(*Channel.globalize_attribute_names) 

視圖助手lang過於簡單化,特別是如果您有許多地區和許多列。留在它的設備只是一個小河...但有點紅寶石和依靠的事實,語言環境始終擔任了,視覺效果顯著改善:

<% Channel.globalize_attribute_names.each do |lang| %> 
    <% if lang[-2, 2] == "it" %> 
    <div class="row highlight"> 
     <h5><%= lang[0..-4] %></h5> 
    <% end %> 
    <div class=" .... columns"> 
     <%= lang[-2, 2] %> 
     <%= f.text_area lang, rows: "3" %> 
    </div> 
  <% if (lang[-2, 2] == "gr") %> 
  </div> 
    <% end %> 
<% end %> 

注:此處顯示的佈局需要遵循語言環境(這裏的順序:第一:它,最後:gr)如application.rb中所定義...以避免任何問題