我的用户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
正确设置为“艺术家”或“听众”?
更新:
我收到此错误:WARNING: Can't mass-assign protected attributes: type
答案 0 :(得分:0)
尝试此功能:
<%= f.fields_for :profile, @user.build_profile(:type => "Artist") do |t| %>
答案 1 :(得分:0)
我的第一个答案很糟糕:
确保您的类型字符串是CamelCased。另外,我认为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
答案 2 :(得分: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
这只是一个例子。