Rails 4 Nested Form with One to One Relationship - ruby-on-rails-4

I have two models with a one to one relationship, User and Author.
I have two issues: the author instance isn't saving, and user.name isn't saving (although other attributes are). I think it is a permission error because the logs say:
Unpermitted parameters: name, authors
I was trying to follow this: How to save form data to different models with one-to-one relationship in rails 3?
User.rb
has_one :author
accepts_nested_attributes_for :author
Author.rb
belongs_to :user
authors#new
<%= simple_form_for #user do |f| %>
<%= f.input :name %>
<%= f.input :email %>
<%= f.input :password %>
<%= f.input :password_confirmation %>
<%= f.simple_fields_for :author do |author_form| %>
<%= author_form.input :bio %>
<% end %>
<%= f.submit %>
<% end %>
Users_Controller
def user_params
params.require(:user).permit(:name, :email, :image,
author_attributes: [:id, :bio,])
end

User controller should look like this:-
def new
#user = User.new
#user.build_author
end
def create
#user = User.new(user_params)
if #user.save
redirect_to success_path
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, author_attributes: [:id, :bio])
end
Users#new
<%= simple_form_for #user do |f| %>
<%= f.input :name %>
<%= f.input :email %>
<%= f.input :password %>
<%= f.input :password_confirmation %>
<%= f.simple_fields_for :author do |author_form| %>
<%= author_form.input :bio %>
<% end %>
<%= f.submit %>
<% end %>

I'm using the Devise gem and found the solution to be adding this code to the Application Controller:
before_action :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email, :password, author_attributes: [:id, :bio]) }
end

Related

Creating new record through fields for within Rails 4

I'm attempting to create a new oil production within the production information page. The fields are appearing but I am unable to get the oil production to save. Any help is appreciated
Productioninfos_controller.rb
def index
#productioninfos = Productioninfo.all
end
def new
#productioninfo = Productioninfo.new
end
def productioninfo_params
params.require(:productioninfo).permit(:firstproduction, :lastproduction, :numberofcompl, :totaldepth, :productionzone, oilproductioninfos_attributes: [:id, :oilcum, :avgbpmlastsixmonths, :avgbpodlastsixmonths])
end
Productioninfo.rb (model)
has_many :oilproductioninfos
accepts_nested_attributes_for :oilproductioninfo, :allow_destroy => :true, :reject_if => :blank
Oilproductioninfo.rb (model)
belongs_to :productioninfo
Productioninfos_form.html.erb
<%= f.fields_for :oilproductioninfos do |ff| %>
<div>
<%= ff.label :oilcum %>
<%= ff.text_field :oilcum %>
<%= ff.label :avgbpmlastsixmonths %>
<%= ff.text_field :avgbpmlastsixmonths %>
<%= ff.label :avgbpodlastsixmonths %>
<%= ff.text_field :avgbpodlastsixmonths %>
</div>

Nested attributes text field isn't showing up in my views

I am new to the rails community. I am working on an application where users can have username with a nested attribute of first and last name. The other text field associated with the User model works fine.
Any help would be much appreciated.
Attached are the app models, controllers, migration files, db schema, and 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 do |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 do |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 do |f| %>
<%= f.fields_for #new_user do |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 do |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 this
controller
def new
#new_user = User.new
#new_user.usernames.build
end
view
<%= form_for #new_user do |f| %>
# ...
<%= f.fields_for :usernames do |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

Nested Form for Devise User

I have devise up and running and everything is work fine, I'm trying to accept_nested_attributes for the user model. I generated a model called degree:
rails g model Degree university:string course:string level:string user:references
rake db:migrate
The form is showing correct but no data is getting saved to the database? in the rails console i ran:
Degree.all
to see if any data is being saved but i get nothing?
registration_controller.rb:
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, :password_confirmation,
:fname, :mname, :lname, :twitterLink, :githubLink, :stackoverflowLink, :dribbleLink, :mediumLink, degree_attributes: [:university, :course, :level]) }
#devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:fname, :mname, :password, :current_password, :lname) }
end
end
Models
class Degree < ActiveRecord::Base
belongs_to :user
end
----------------------------------
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :degrees
accepts_nested_attributes_for :degrees
end
form where nested attributes are:
<h2>Sign up</h2>
<% resource.degrees.build %>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<div class="field">
<%= f.label :password %>
<% if #minimum_password_length %>
<em>(<%= #minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="field">
<%= f.fields_for :degree do |degree_fields| %>
<%= degree_fields.label :university %>
<%= degree_fields.text_field :university %><br>
<%= degree_fields.label :course %>
<%= degree_fields.text_field :course %><br>
<%= degree_fields.label :level %>
<%= degree_fields.text_field :level %><br>
<% end %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
degree_controller.rb
class DegreeController < ApplicationController
def new
#user = User.new
#user.degrees.build(degree_params)
end
def create
#user.degrees.build(degree_params)
end
private
def degree_params
params.require(:degree).permit(:university, :degree, :level)
end
end

Remove avatar - carrierwave and devise

I'm having an unbelievable amount of trouble getting the Carrierwave :remove_avatar checkbox to work in my Devise profile edit form. I've been following the carrierwave documentation and wiki.
I've mounted the uploader to the User model. I've added :avatar and :remove_avatar to in the ApplicationController sanitizer
application_controller.rb
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) do |u|
u.permit(:first_name, :last_name, :email,
:password, :password_confirmation, :avatar, :remove_avatar)
end
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:first_name, :last_name, :email,
:password, :password_confirmation)
end
end
I've added the :remove_avatar to the edit form
/devise/registrations/edit.html.erb
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put, multipart: true }) do |f| %>
<%= f.label :avatar %><br />
<%= image_tag(resource.avatar_url(:thumb)) %>
<%= f.file_field :avatar, accept: 'image/jpeg,image/png' %>
<label>
<%= f.check_box :remove_avatar %>
Remove avatar
</label>
<%= f.label :first_name %><br />
<%= f.text_field :first_name, autofocus: true %>
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
<%= f.label :email %><br />
<%= f.email_field :email %>
<div><%= link_to 'Cancel', resource %> <%= f.submit "Update" %></div>
<% end %>
I'm not having any other problems with carrierwave except for removing the avatars. When I check the box and submit the form the picture is not removed.
I did a test where I used the users controller instead of devise's registrations controller and submitted the form to #user instead of resource and I was able to get it working. I'd rather stick to convention and use the registrations controller. What am I doing wrong or missing?
#user.remove_avatar!
#user.remove_avatar = true
#user.save
#user.reload
Try this, May help you.
Use this in your model:
after_commit :remove_avatar!, on: :destroy

errors messages doesn't work in HTML ruby code

I am using rails 4.1.6 I looked at the active record validations site and follow their direction, but nothing is displayed in the HTML even if there is an error.
However, when I do it in rails console it works.
post = Post.new #create an empty post to test
post.valid? #false
post.errors.messages #this is successfully generate the error message array
However, it doesn't display any error messages in HTML. In fact "#post.errors" doesn't even run
-Ruby code in html
<%= form_for #post, :method => :post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :url %>
<%= f.text_field :url %>
<%= f.submit "Submit" %>
<% if #errors.any? %>
<ul>
<% #errors.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<% end %>
-My PostsController
def create
# post = Post.new(title: params[:post][:title], url: params[:post][:url])
post = Post.new(post_params)
if post.save
redirect_to posts_path
else
#errors = post.errors.messages
redirect_to paths_path
end
end
private
def post_params
params.require(:post).permit(:title, :url)
end
-My post model
class Post < ActiveRecord::Base
validates :title, :length => {maximum: 140, minimum:1}, :presence => true
validates :title, :length => {maximum: 2083, minimum:1}, :allow_blank => true
end
When it comes to errors I do like to have a partial so I can keep my errors the same in the whole app like so:
app/views/shared/_errors.html.erb:
<% if object.errors.any? %>
<h5>The <%= t("activerecord.models.#{object.class.to_s.downcase}") %> could not be saved due to the following errors:</h5>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
And then for the views you want the errors to be displayed, just call:
<%= render 'shared/errors', object: #your_object %>
Hope this helps!
thanks for your help. Got some tip from my teacher it work. Simply use flash[:message] and it worked. Sorry for the trouble everyone
-My controller code
def create
post = Post.new(post_params)
if post.save
redirect_to :back
else
flash[:message] = post.errors.messages
redirect_to :back
end
end
-My HTML code
<%= simple_form_for #post, :method => :post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :url %>
<%= f.text_field :url %>
<%= f.submit "Submit" %>
<%= flash[:message] %>
<% end %>