I have this ruby code for radio buttons in my user new
form:
<%= 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 %>
I want to set the type
attribute of my Profile model. However, type is not being set and is defaulting to nil
. I tried creating this create
method in my profile controller but it didn't work:
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
How can I get type
to be set to "artist" or "listener" correctly?
UPDATE:
I get this error: WARNING: Can't mass-assign protected attributes: type
I think you want to access it like this:
params[:user][:profile_attributes][:type]
Your view should look something like:
<%= 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 %>
and in your helpers/application_helper.rb
def setup_user(user)
user.tap do |u|
u.build_profile if u.profile.nil?
end
end
This is just an example.
My First Answer was bad:
Make sure your type strings are CamelCased. Also, I believe type is attr_protected meaning you can not set it via attr_accesible.
Something like this may get you going in the right direction:
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
Try this function:
<%= f.fields_for :profile, @user.build_profile(:type => "Artist") do |t| %>
精彩评论