ruby on rails 4 - Nested attributes text field isn't showing up in my views -


i new rails community. working on application users can have username nested attribute of first , last name. other text field associated user model works fine.

any appreciated.

attached app models, controllers, migration files, db schema, , views.

models

class user < activerecord::base   has_one :username, dependent: :destroy   accepts_nested_attributes_for :username, allow_destroy: true  end   class username < activerecord::base   belongs_to :user   end 

migrations

class createusers < activerecord::migration   def change     create_table :users |t|       t.string :email       t.string :about_me       t.string :nationality       t.string :sexe       t.timestamps null: false     end   end end   class createusernames < activerecord::migration   def change     create_table :usernames |t|       add_column :username, :first_name, :string       add_column :username, :last_name, :string       t.references :user, index: true, foreign_key: true       t.timestamps null: false     end   end end 

controller

class userscontroller < applicationcontroller   def index     @all_users = user.all     @new_user = user.new     @username = username.new   end    def new     @new_user = user.new   end    def create     user.create(user_params)   end    private    def user_params     params.require(:user).permit(:email, :about_me, username_attributes:     [:last_name, :first_name])   end end 

views

<h1>users#index</h1> <p>find me in app/views/users/index.html.erb</p>   <%= form_for @new_user |f| %>   <%= f.fields_for @new_user |user| %>     <div class="field">       <%= user.label :email%>       <%= user.text_field :email %>       <%= user.label :about_me %>       <%= user.text_field :about_me %>     </div>     <% end %>     <%= f.fields_for :username |name| %>       <div class="field">         <%= name.label :first_name %>         <%= name.text_field :first_name %>       </div>     <% end %>        <div class="form-actions">         <%= f.button :submit %>       </div>  <% end %> 

try controller

def new     @new_user = user.new     @new_user.usernames.build end 

view

<%= form_for @new_user |f| %>   # ...   <%= f.fields_for :usernames |name| %>     <div class="field">       <%= name.label :first_name %>       <%= name.text_field :first_name %>     </div>   <% end %>   # ... <% end %> 

helper

def name_format(user_mst)     name = user_mst.first_name.capitalize     name += (" #{user_mst.last_name.capitalize}")      return name end 

to display on view


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -