I couldn't find any good tutorial on how to use Activerecord associations with Sinatra. So, I managed to create on in my own style but i am not sure if this is the correct approach. Its working as expected but would appreciate your suggestions. I have two classes Visitors and Users. A visitor can have many users and the visitor can add new users after logging in. Here are the code snippets from the files:
new.erb:
<div class="newuser">
<form id="user" action="/" method="POST" role="form" >
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" name ="email" value="<%= @user.email %>" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<label for="email">Name:</label>
<input type="text" name="fname" value="<%= @user.fname %>" placeholder="Name" class="form-control">
</div>
<input type = "hidden" value ="<%= session[:id] %>" name="visitor_id" >
<input type="submit" value="Submit →" class="btn btn-info">
</form>
</div>
The session id is defined as follows:
@visitor = Visitor.find_by_usernameemail(params[:usernameemail])
session[:id] = @visitor.id
Now my models.rb file is as follows:
class User < ActiveRecord::Base
validates :fname, presence: true
validates :email, presence: true
belongs_to :visitor
end
class Visitor < ActiveRecord::Base
validates :usernameemail, presence: true
validates :password, presence: true
has_many :users
end
the User Id route is written as follows:
get '/user/:id' do
if User.exists?(params[:id])
@user = User.find(params[:id])
if @user.visitor_id == session[:id]
erb :user
else
"Your are not allowed to access this page"
end
else
"record not found"
end
end
Now using the above approach, is it really necessary to use has_many and belongs_to and is this the proper way of doing it? Also, it would be great if you could point me to a resource on how to use has_many and belongs_to like associations in Sinatra with activerecord.
Aucun commentaire:
Enregistrer un commentaire