2011-03-27 86 views
0

我有一個單選按鈕這個Ruby代碼在我的用戶new形式:屬性沒有被設置

<%= f.fields_for :profile, Profile.new do |t| %> 
<div class ="field"> 
    <%= t.label :type, "Are you an artist or listener?" %><br /> 
    <p> Artist: <%= t.radio_button :type, "artist" %></p> 
    <p> Listener: <%= t.radio_button :type, "listener" %></p> 
    </div> 
<% end %>  

我想設置我的剖面模型的type屬性。但是,類型未設置,默認爲nil。我想在我的個人資料控制器創建這個create方法,但它沒有工作:

def create 
    @profile = Profile.find(params[:id]) 
    if params[:profile_attributes][:type] == "artist" 
    @profile.type = "artist" 
    elsif params[:profile_attributes][:type] == "listener" 
    @profile.type = "listener" 
    end 
end 

我怎樣才能得到type設置爲「藝術家」或「監聽器」是否正確?

UPDATE:

我得到這個錯誤:WARNING: Can't mass-assign protected attributes: type

+0

您是否使用STI? – 2011-03-27 22:21:04

+0

是的,我正在使用STI – 2011-03-27 22:22:25

回答

0

我想你要訪問它像這樣:

params[:user][:profile_attributes][:type] 

你的觀點應該是這個樣子:

<%= form_for(setup_user(@user)) do |f| %> 
    <p> 
    <%= f.label :email %> 
    <br/> 
    <%= f.text_field :email %> 
    </p> 
    <%= f.fields_for :profile do |profile| %> 
    <%= profile.label :username %> 
    <br/> 
    <%= profile.text_field :username %> 

和你的助手/ application_helper.rb

def setup_user(user) 
    user.tap do |u| 
     u.build_profile if u.profile.nil? 
    end 
    end 

這僅僅是一個例子。

+0

感謝,但我似乎仍不能得到'type'進行設置.. 。請問您可以向我展示我應該使用的表單代碼和控制器代碼...我必須得到錯誤 – 2011-03-27 23:36:07

+0

更新的答案。 – 2011-03-28 00:37:30

+0

怎麼樣控制器代碼來設置'type'?由於某種原因仍然不能設置... – 2011-03-28 00:49:49

0

試試這個功能:

<%= f.fields_for :profile, @user.build_profile(:type => "Artist") do |t| %> 
+0

我是否需要那些控制器代碼,或者我可以取消它? – 2011-03-27 22:23:02

+0

,我也可以擺脫'before_create:build_profile'回調呢? – 2011-03-27 22:23:39

+0

我應該自動設置類型爲藝術家?這似乎沒有工作.. – 2011-03-27 22:38:14

0

我的第一個答案是壞:

確保您的類型字符串駝峯格式。另外,我相信type是attr_protected,意思是你不能通過attr_accesible來設置它。

像這樣的東西可以讓你在正確的方向前進:

class ProfilesController < ApplicationController 
    def create 
    @profile = profile_type.new(pararms[:profile]) 
    if @profile.save(params[:profile]) 
     # ... 
    else 
     # ... 
    end 
    end 

private 

    def profile_type 
    params[:profile][:type].classify.constantize if %w(Artist Listener).include? params[:profile][type] 
    end 

end 
+0

更正類型。將屬性_type_重命名爲_profile_type_將繞過這個問題。 _type_屬性用於單表繼承(STI),在模型中創建屬性時不應使用_type_屬性。請參閱文檔中的「單表繼承」部分獲取更多信息http://api.rubyonrails.org/classes/ActiveRecord/Base.html – scarver2 2012-07-08 03:51:04