2011-03-27 144 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

相关问题