"first" helper method - ruby

I've been looking at a project for a login module, but I'm not sure exactly what this helper method is doing:
def self.authenticate(login, pass)
u = User.first(:login => login)
return nil if u.nil?
return u if User.encrypt(pass, u.salt) == u.hashed_password
nil
end
Why not instead of:
u = User.first(:login => login)
...you do something like:
u = self.login
Thanks!

The first helper method locates the first record in your database that matches the specified criteria. It's semantically equivalent to the following SQL statement:
SELECT * FROM Users WHERE login = 'foo' LIMIT 1
The code after u = User.first(:login => login) does the following:
1. Checks to see if there is a user returned with the specified login
2. Returns the User object if the passwords match.

u = User.first(:login => login)
means "go to the database, and find me the first User object whose login equals the userid passed in as the "login" parameter. Assign this to u.

Because you're looking for the corresponding user object, not just the login name.

Related

Ecto.Repo to check if id exists in the database, Phoenix framework

How do I check if an id exists in the database?
def get_user!(id), do: Repo.get!(User, id)
get_user!(id) can be used to get the user, is there a way to check if id exists?
I want something like below which would return true.
MyApp.Accounts.get_user!(user_id) == %MyApp.Accounts.User{id: user_id}
Ecto v3 supports this with Ecto.Repo.exists?/2
import Ecto.Query, only: [from: 2]
Repo.exists?(from u in User, where: u.id == ^user_id)
Repo.get! throws an error if no record is found.
You might want to use Repo.get instead like
Repo.get(User, user_id) != nil
You can also define a function to check if a give user id exists
def user_exist_by_id(user_id)do
#select just id to reduce payload
query = (from u in User, where: u.id == ^user_id, select: %{id: u.id})
found = Repo.one(query)
#if not result, found will be nil
found != nil
end

Spring #Query with principal and ternary operator

#Query("select p from Person p where p.id=?#{principal=='anonymousUser'?0:principal.id})")
public Person getCurrentUser();
This method is intended to return a current user/person or nothing (there is no user with id=0 in the database) if the user is anonymous. And it works fine in the first case, but when the user is anonymous it gives an error:
org.hibernate.QueryException: Not all named parameters have been set:
[1] [select p from Person p where p.id=?1)]
It seems it expects some parameters now, but why? Shouldn't the query be
select p from Person p where p.id=0
?
It seems it will work if you replaces 0 by null

Unable to create a constant value of type 'IdentityUserRole'. Only primitive types or enumeration types are supported

In my ASP.NET MVC 5 application I want to list the roles of a user. I downloaded some samples that seem to be broken. Basically I want both the role ID and role name of the roles of a selected user (not the current user!).
ApplicationUser.Roles gives me an IdentityUserRole object with only RoleId and UserId.
ApplicationDbContext.Roles gives me an IdentityRole with RoleId, RoleName etc. of ALL application roles.
So what I want is a result set with the intersection of both sets while retaining full role information so that I can use both its role ID and role name.
I tried Intersect() but that didn't work because both objects are of different type. I tried the dumb style of iterating but got an exception saying the DAta Reader was already active so I am stumped :(
I tried the following on LinQPad (with the appropriate conenctions and namespaces):
string UserName = "user#email.com";
ApplicationDbContext ctx = new ApplicationDbContext();
var allroles = ctx.Roles.OrderBy(r => r.Id);
allroles.Dump(); // dumps well, 6 roles
ApplicationUser user = ctx.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var myroles = user.Roles;
myroles.Dump(); // dumps well, 3 roles
IEnumerable<IdentityRole> list = from roles in allroles
join uroles in myroles
on roles.Id equals uroles.RoleId
select roles;
list.Dump(); // exception
And while the query seems to produce no error during execution, its dumping does regardless of whether I use Dump() or an explicit foreach (IdentityRole item in list). The error I get in this case is
"Unable to reate a constant value of type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole'. Only primitive types or enumeration types are supported in this context".
The only problem here is that you are not calling ToList() method which execute the query immediately (everything will be held in the memory).
For better understanding - ToList() method converts an IEnumerable<T> to a List<T>.
So, your code will look like this:
var allroles = ctx.Roles.OrderBy(r => r.Id).ToList();
var myroles = user.Roles.ToList();
You could use a combination of the two approaches you tried, where you get roles from the context that are present in the ApplicationUser's Roles property...
var roles = ApplicationDbContext.Roles
.Where(ar =>
ApplicationUser.Roles
.Select(ur =>
ur.RoleId)
.Contains(ar.RoleId));
You can do this way :
var rolesList = allroles.ToList().Join(myroles.ToList(),
left => left.Id,
right => right.RoleId,
(left,right) => left);
This way it is working for me for different scenario.
You're trying to join an in-memory list, myroles, with an IQueryable, allroles, which produces a new IQueryable: list. However, this new IQueryable is translated into SQL, so myroles must be translated into SQL as well. This is not supported for lists of non-primitive types.
The solution is to join two IQueryables:
var myroles = ctx.Users.Where(u => u.UserName == UserName).SelectMany(u => u.Roles);
var list = from role in allroles
join urole in myroles
on role.Id equals urole.RoleId
select role;

Django form query

I saw this piece of code and have few questions..If anyone could explain that would be really helpful.
views.py
def search_page(request):
pdb.set_trace()
form = SearchForm()
bookmarks = []
show_results = False
if 'query' in request.GET:
show_results = True
query = request.GET['query'].strip()
if query:
form = SearchForm({'query': query})
bookmarks = Bookmark.objects.filter(title__icontains=query)
variables = RequestContext(request,{'form': form,
'bookmarks': bookmarks,
'show_results': show_results,
'show_tags': True,
'show_user': True})
return render_t7tr o_response('search.html', variables)
form.py
class SearchForm(forms.Form):
query = forms.CharField(label=u'Enter a keyword to search for', widget=forms.TextInput(attrs={'size':32}))
How do the below line of code work?
If 'query' in request.GET
how the 'query' string is in the request.Get?..When I debugged the dictionary contains the value contains the search value I have given.
THe code works fine but I want to understand.
Containment testing on mappings checks the keys.
key in d
Return True if d has a key key, else False.
EDIT:
Django parses the query string and populates request.GET from it.

C# Excluding related values from a list (LINQ)

Is there an exact opposite action to "join" in linQ to SQL? I want to display just the results that do not fulfill the inner join constraint from a query. I wanna do it just in one query. Here's an example of it's use (http://img165.imageshack.us/img165/4940/liststj3.jpg).
Falvarez's roles:
Roles.Where(r => r.Users.Any(u => u.Name == "falvarez"));
Roles that falvarez doesn't have
Roles.Where(r => !r.Users.Any(u => u.Name == "falvarez"));
Project each role into an object that knows whether falvarez is in that role
Roles.Select(r => new
{
FalvarezInRole = r.Users.Any(u => u.Name == "falvarez"),
Role = r
});
In the case that the role object doesn't have a users property, simply substitute a query that filters users by role in the place of r.Users
Bilal Haidar has an explanation on how to do a left outer join. Use this strategy and add a where condition to check where the object on the right hand side is null.
Check out Zip here:
http://www.codeplex.com/nextension
EDIT: might be better off doing "where !Collection.Contains(s.ID)" ...

Resources