Ive looked at atleast 8 other forums with the same title and none of the ones read helped me at all!
So im using a partial to render a form to a edit.html.erb page and a new.html.erb page. My controller page works except for the edit page!
Here is my code for my controller page :
class ProfilesController < ApplicationController
def new
# form where a user can fill out their own profile.
#user = User.find( params[:user_id] )
#profile = Profile.new
end
def create
#user = User.find( params[:user_id] )
#profile = #user.build_profile(profile_params)
if #profile.save
flash[:success] = "Profile Updated!"
redirect_to user_path( params[:user_id] )
else
render action: :new
end
end
def edit
#user = User.find( params[:id] )
#profile = #user.profile
end
private
def profile_params
params.require(:profile).permit(:first_name, :last_name, :job_title, :phone_number, :contact_email, :description)
end
end
my edit.html.erb page:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">Edit Your Profile</h1>
<p class="text-center">Be a part of the Dev Match community and fill out your profile!</p>
<div class="well">
<%= render 'form' %>
</div>
</div>
</div>
my new.html.erb page:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">Create Your Profile</h1>
<p class="text-center">Be a part of the Dev Match community and fill out your profile!</p>
<div class="well">
<%= render 'form' %>
</div>
</div>
</div>
and _form.html.erb:
<%=form_for (#profile) , url: user_profile_path do |f| %>
<div class="form-group">
<%= f.label :first_name %>
<%= f.text_field :first_name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :last_name %>
<%= f.text_field :last_name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :job_title %>
<%= f.select :job_title, ['Developer', 'Entrepreneur', 'Investor'], {}, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :phone_number %>
<%= f.text_field :phone_number, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :contact_email %>
<%= f.text_field :contact_email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.submit "Update Profile", class: 'btn btn-primary' %>
</div>
<% end %>
You change your code into this:
def edit
#user = User.find(params[:user_id])
#profile = #user.profile
end
#user is null because the id does not exist in DB.
If you create a new instance of User in the action new you can use the same object in the action create without use the method User.find
As improvement, try to add before_action in your controller.
class ProfilesController < ApplicationController
before_action :prepare_model, except: [:new, :create]
def new
# form where a user can fill out their own profile.
#user = User.new
#profile = Profile.new
end
def create
#profile = #user.build_profile(profile_params)
if #profile.save
flash[:success] = "Profile Updated!"
redirect_to user_path( params[:user_id] )
else
render action: :new
end
end
def edit
#profile = #user.profile
end
private
def prepare_model
#user = User.find(params[:user_id])
raise ActiveRecord::RecordNotFound if #user.nil?
end
def profile_params
params.require(:profile).permit(:first_name, :last_name, :job_title, :phone_number, :contact_email, :description)
end
end
Related
I am working in a Rails Project and my problem is that for some reason the home view shows the SQL Query next to the book image.
Here is the HTML code that shows the index view
<div id="books-index">
<% #books.each_slice(4) do |book| %>
<div class="row">
<%= book.each do |book| %>
<div class="col-md-3 col-sm-3">
<h3><%= book.title %></h3>
<%= image_tag(book.coverpath) %>
<%= link_to 'Read More', book_path(book), class:"btn btn-primary" %>
</div>
<% end %>
</div>
<% end %>
</div>
and the books controller
class BooksController < ApplicationController
def new
#page_title = 'Add Book'
#book = Book.new
#category = Category.new
#author = Author.new
#publisher = Publisher.new
end
def create
#book = Book.new(book_params)
if #book.save
flash[:notice] = "Book Created"
redirect_to books_path
else
render 'new'
end
end
def index
#books = Book.all
end
private
def book_params
params.require(:book).permit(:title, :category_id, :author_id, :publisher_id, :isbn, :price, :buy, :format, :excerpt, :pages, :year, :coverpath)
end
end
Thanks a lot for your help
Remove the = on your book.each iteration:
<% #books.each_slice(4) do |book| %>
<div class="row">
<% book.each do |book| %>
...
<% ... %> just evaluated, not printed.
<%= ... %> evaluated and printed.
So I have two models, User and Employee. User has one employee and Employee belongs to User. I want to create an employee but first I have to create a new User. My Employee model does not have the attributes :email, :password, :password_confirmation so I created virtual attributes. This is the error that pops up Validation failed: Email is invalid, Password confirmation doesn't match Password
here is my employee model
class Employee < ApplicationRecord
belongs_to :user
attr_accessor :email, :password, :password_confirmation
validates :email, format: { with: /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :password, confirmation: true
end
my employee controller
class EmployeesController < ApplicationController
def create
#newuser=User.create!(
email: :email,
password: :password,
password_confirmation: :password_confirmation
)
#employee = Employee.new(employee_params)
respond_to do |format|
if #employee.save
format.html { redirect_to #employee, notice: 'Employee was successfully created.' }
format.json { render :show, status: :created, location: #employee }
else
format.html { render :new }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
private
def employee_params
params.require(:employee).permit(:name, :contact_no, :role_id, #newuser.id)
end
end
And my form
<%= form_for(employee) do |f| %>
<% if employee.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(employee.errors.count, "error") %> prohibited this employee from being saved:</h2>
<ul>
<% employee.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :email %>
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
</div>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :contact_no %>
<%= f.text_field :contact_no %>
</div>
<div class="field">
<%= f.label :role_id %>
<%= f.number_field :role_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I'm still learning rails and would greatly appreciate your help
if you don't have attributes :email, :password, :password_confirmation then remove the following validation:
validates :email, format: { with: /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :password, confirmation: true
from Employee Model.
I have found the solution to my problem, it seems that my user parameters weren't following rails' strong parameters rule. so my controller has this now
def employee_params
params.require(:employee).permit(:name, :contact_no, :role_id)
end
def user_params
params.require(:employee).permit(:email, :password, :password_confirmation)
end
I was then able to make the user using the parameters without a problem.
new.html is a registration form ,which creates tutor account .
It involves error handling . _error_messages.html.erb is the file which handles the error ,like should be filling in all text fields .
e.g , showing :
`
The form contains 3 errors.
Name can't be blank
Password confirmation can't be blank
Password confirmation doesn't match Password
However ,when submits the form without any input in new.html ,it shows the error
Missing template tutors/register, application/register with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.0.0/lib/action_dispatch/templates" * "D:/Sites/abc/app/views"
new.html.erb
<% provide(:title, 'Registeration') %>
<h1>Tutor Registration</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(#tutor) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control' %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.label :gender %>
<%= f.select(:gender, ['Male', 'Female'] , class: 'form-control' )%>
<%= f.label :tutor_education_level %>
<%= f.select(:education_level, ['Bachelor', 'Master', 'Doctor'] , class: 'form-control' )%>
<%= f.label :tutor_institution %>
<%= f.text_field :institution, class: 'form-control' %>
<%= f.label :tutorial_experience %>
<%= f.text_field :experience, class: 'form-control' %>
<%= f.label :tutor_preferred_district %>
<%= f.text_field :district, class: 'form-control' %>
<%= f.label :tutor_preferred_subject %>
<%= f.text_field :subject, class: 'form-control' %>
<%= f.label :tutor_required_student_level %>
<%= f.select(:student_level, ['P1-P3', 'P4-P6', 'S1-S3', 'S4-S6'] , class: 'form-control' )%>
<%= f.submit "Create tutor's account", class: "btn btn-primary" %>
<% end %>
</div>
</div>
views/shared/_error_messages.html.erb
<% if #tutor.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(#tutor.errors.count, "error") %>.
</div>
<ul>
<% #tutor.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Tutor -controller
class TutorsController < ApplicationController
before_action :logged_in_tutor, only: [:edit, :update]
before_action :correct_tutor, only: [:edit, :update]
def index
#tutors = Tutor.all
end
def show
#tutor = Tutor.find(params[:id])
end
def new
#tutor = Tutor.new
end
def create
#tutor = Tutor.new(tutor_params)
if #tutor.save
log_in #tutor
flash[:success] = "Congratulations! Your registration is successful!"
redirect_to #tutor
else
render 'register'
end
end
def edit
#tutor = Tutor.find(params[:id])
end
def update
if #tutor.update_attributes(tutor_params)
flash[:success] = "Profile updated successfuly!"
redirect_to #tutor
else
render 'edit'
end
end
# Handle sign-up failure, to redirect the tutor to the registeration form again
def tutor_params
params.require(:tutor).permit(:name, :email, :password, :password_confirmation, :address,:gender ,:education_level,:institution,:exprience,:district,:subject,:student_level)
end
def logged_in_tutor
unless logged_in?
store_location
flash[:danger] = "Please log in."
redirect_to login_url
end
end
def correct_tutor
#tutor = Tutor.find(params[:id])
redirect_to(root_url) unless current_tutor?(#tutor)
end
end
When you submit the form, request sends to the create action:
def create
#tutor = Tutor.new(tutor_params)
if #tutor.save
# if #tutor valid save it and redirect to show action
redirect_to #tutor
else
# else render the register template(or action)
render 'register'
end
end
In the create action there is a conditional if, in the first case all is good, #tutor has been saved and Rails call redirect to show action, otherwise Rails trying to render register template which is not exists(the errors claims about it). To resolve that issue create register template with desired html code which should run if #tutor isn't saved.
I am using <% #articles.each do |article| %> do display all articles which is working however it is also displaying '/subs/27/articles' as one of the articles. When I click it it goes to my index view. Why is this link showing here with all the articles
```
class SubsController < ApplicationController
def show
#sub = Sub.find(params[:id])
#category = Category.find(params[:category_id])
#articles = #sub.articles
#article = #sub.articles.build
end
def new
#category = Category.find(params[:category_id])
#sub = Sub.new
end
def create
#category = Category.find(params[:category_id])
#sub = Sub.new(params.require(:sub).permit(:title))
#sub.category = #category
if #sub.save
flash[:notice] = "Subcategory was saved"
redirect_to [#category, #sub]
else
flash[:error] = "The Subcategory could not be saved"
render :new
end
end
def edit
#category = Category.find(params[:category_id])
#sub = Sub.find(params[:id])
end
def update
#category = Category.find(params[:category_id])
#sub = Sub.find(params[:id])
#sub.category = #category
if #sub.update_attributes(params.require(:sub).permit(:title))
flash[:notice] = "Subcategory was saved"
redirect_to [#category, #sub]
else
flash[:error]= "The subcategory could not be saved"
render :edit
end
end
def sub_params
params.require(:sub).permit(:title)
end
views/subs/show.html.erb
<h1 align="center"><%= #sub.title %></h1>
<div class="row">
<div class="col-md-8">
<%= link_to "Back", :back, class: "btn btn-default" %>
<% if user_signed_in? %>
<%= link_to "Edit", edit_category_sub_path(#category, #sub), class: "btn btn-success" %>
<% else %>
<% end %>
</div>
<!--
<div class="col-md-4">
<%= link_to "New Article", new_category_sub_path(#category), class: 'btn btn-success' %>
</div>
-->
</div>
<hr>
<br>
<div class="row">
<% #articles.each do |article| %>
<div class="col-xs-3">
<div class="tile" >
<h5 align="center">
<%= link_to article.title, [#sub, article] %>
</h5>
</div>
</div>
<% end %>
</div>
<% if user_signed_in? %>
<div class="col-md-12">
<%= render 'articles/form', category: #category, article: #article, sub: #sub %>
</div>
<% else %>
<% end %>
<!--
<div class="col-md-12">
<%= render 'articles/form', category: #category, article: #article, sub: #sub %>
</div>
-->
```
After you gave me more information,
I think this is your problem right here:
#sub.articles.build
It is building a new unsaved article association and then later it iterates through articles, including that unsaved record, hence why the title is empty.
I'm using Carrierwave with Rails to upload and display images. I've been using it for articles and other parts of my site without a problem but for some reason it's not working for the model I just created. I can see the space for the image tag rendered without the image and then disappear quickly when the page loads. Nothing like this has occurred until I tried it with this model which isn't much different from my other models:
class Ad < ActiveRecord::Base
validates_numericality_of :zip_code
validates_presence_of :image, :advertiser
mount_uploader :image, ImageUploader
end
My create and index actions:
def create
#ad = Ad.new(params[:ad].permit(:image, :advertiser, :zip_code))
if #ad.save
redirect_to :back
else
flash[:error] = "Invalid input"
redirect_to :back
end
end
def index
#new_ad = Ad.new
#ads = Ad.all.reverse
end
My _new partial:
<div id="card">
<%= form_for #new_ad, html: {multipart: true, "data-ajax" => false} do |f| %>
<p>
<%= f.file_field :image %>
</p>
<p>
<%= f.text_field :advertiser, placeholder: "Advertiser" %>
</p>
<p>
<%= f.text_field :zip_code, placeholder: "Zip code" %>
</p>
<p>
<%= f.submit "Upload" %>
</p>
<% end %>
</div></br>
My index view:
<%= render "new" %>
<% for ad in #ads %>
<div id="card">
<div align="center">
<%= image_tag ad.image %>
<%= ad.advertiser %>
<%= ad.zip_code %>
</div>
</div></br>
<% end %>
As per my understanding problem is with your index view.
<%= image_tag ad.image %>
you are using ad.image this will return you imageuploader object not image path. So instead of using ad.image you can use ad.image.url(relative path) or ad.image.current_path(absolute path)
<%= image_tag ad.image.url %>