After several hours of work, I cannot save the database.
The context is this: I have two types of users: for this I need only basic information [Username, email address, password] and another kind of user for which I need more information [age, gender, city, etc.]
I did not use STI because of the huge number of null values that would be in the table. Therefore, I created three modes in which the user has a profile (profile table) or not depending on its type [1 or 2], and the field of this profile is the city in which this user lives, which belongs to another table in the database, table of cities
class User < ActiveRecord::Base
has_one :profile
has_one :city, through: :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :city
[...a bunch of fields here]
end
class City < ActiveRecord::Base
has_many :profiles
has_many :users, through: :profiles
end
When I play with them in the rails console, everything goes fine:
usr = User.new(name: "roxy", email: "roxy@example.me", password: "roxanna", password_confirmation: "roxanna", utype: 1)
cty = City.new(name: "Bucaramanga")
prf = Profile.new (rname: "Rosa Juliana Diaz del Castillo"...)
prf.city = cty
usr.profile = prf
usr.valid?
=> true
usr.save
=> true
( )
<%= f.label :city, "En que ciudad te encuentras?"%>
<%= select_tag :city, options_from_collection_for_select(City.all, 'id', "name"),{:prompt => 'Selecciona tu ciudad'}%>
def new
@profile = Profile.new
end
def create
@profile = params[:profile]
@city= City.find_by_id(params[:city].to_i)
@profile.city = @city
end
:
undefined method `city=' for #<ActiveSupport::HashWithIndifferentAccess:0xa556fe0>
- ?
UPDATE
, Profile create, :
def create
@profile = Profile.new(params[:profile])
@city= City.find_by_id(params[:city].to_i)
@profile.city = @city
@usr = current_user
if @usr.profile.exists? @profile
@usr.errors.add(:profile, "is already assigned to this user")
render :new
else
@usr.profile << @profile
redirect_to root_path
end
end
undefined method `exists?' for nil:NilClass
current_user @current_user
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
, ?