Rails 4.2.11, User.find_by(name: 'name', email: 'email') returning array, not instance - ruby-on-rails-4

In Rails 4.2.11,
User.find_by(name: 'name', email: 'email')
is returning an ActiveRecord::Relation (containing array of one User instance) instead of one instance of User.
#<ActiveRecord::Relation [#<User id: 1, name: "Tester Test", email: "stester#xxx.xxx", created_at: "2021-04-27 14:08:49", updated_at: "2021-04-27 14:08:49">]>
This is happening in the context of a failing cucumber test where I create an authorization record and a user record. The authorization record is found, but the user record comes back only as a Relation no matter what I do. Tried .first, .take, several other ways to retrieve the instance.
This is identical to the output of User.where, not User.find_by. Any idea why this is happening???

And if you add '.first' like:
User.find_by(name: 'name', email: 'email').first
works for you?

Everything is working now, after I stopped running the test for about 10 minutes. My only explanation is that there sometimes seems to be a discrepancy between my current code and what my ide terminal thinks it sees when my internet is glitchy.
I had originally used a where just to get an idea if it was working properly (to show myself that it was only going to return one valid record). Then I modified it to be find_by (what I actually wanted), but it kept on returning results as if the where was still there. Then, bingo, it started to behave as expected. ???
My only explanation is these intermittent outages are affecting the internet connection to my ide.

Related

Rails 4 Action Mailer Previews and Factory Girl issues

I've been running into quite an annoying issue when dealing with Rails 4 action mailer previews and factory girl. Here's an example of some of my code:
class TransactionMailerPreview < ActionMailer::Preview
def purchase_receipt
account = FactoryGirl.build_stubbed(:account)
user = account.owner
transaction = FactoryGirl.build_stubbed(:transaction, account: account, user: user)
TransactionMailer.purchase_receipt(transaction)
end
end
This could really be any action mailer preview. Lets say I get something wrong (happens every time), and there's an error. I fix the error and refresh the page. Every time this happens I get a:
"ArgumentError in Rails::MailersController#preview
A copy of User has been removed from the module tree but is still active!"
Then my only way out is to restart my server.
Am I missing something here? Any clue as to what is causing this and how it could be avoided? I've restarted my server 100 times over the past week because of this.
EDIT: It may actually be happening any time I edit my code and refresh the preview?
This answers my question:
https://stackoverflow.com/a/29710188/2202674
I used approach #3: Just put a :: in front of the offending module.
Though this is not exactly an answer (but perhaps a clue), I've had this problem too.
Do your factories cause any records to actually be persisted?
I ended up using Factory.build where I could, and stubbing out everything else with private methods and OpenStructs to be sure all objects were being created fresh on every reload, and nothing was persisting to be reloaded.
I'm wondering if what FactoryGirl.build_stubbed uses to trick the system into thinking the objects are persisted are causing the system to try and reload them (after they are gone).
Here's a snippet of what is working for me:
class SiteMailerPreview < ActionMailer::Preview
def add_comment_to_page
page = FactoryGirl.build :page, id: 30, site: cool_site
user = FactoryGirl.build :user
comment = FactoryGirl.build :comment, commentable: page, user: user
SiteMailer.comment_added(comment)
end
private
# this works across reloads where `Factory.build :site` would throw the error:
# A copy of Site has been removed from the module tree but is still active!
def cool_site
site = FactoryGirl.build :site, name: 'Super cool site'
def site.users
user = OpenStruct.new(email: 'recipient#example.com')
def user.settings(sym)
OpenStruct.new(comments: true)
end
[user]
end
site
end
end
Though I am not totally satisfied with this approach, I don't get those errors anymore.
I would be interested to hear if anyone else has a better solution.

Ember Data: Trying to make a Child Record persist in Rails 4 backend

I've searched a lot for an answer to this, and I feel like I'm close...
I have Quiz, Question, and Answer models.
Rails--
Quiz has_many Questions
Question has_many Answers
Ember--
Quizzmob.Quiz = DS.Model.extend
title: DS.attr('string')
questions: DS.hasMany('question')
Quizzmob.Question = DS.Model.extend
prompt: DS.attr('string')
quiz: DS.belongsTo('quiz')
I'm able to persist a new quiz to my Rails backend just fine with a simple save().
I've also sideloaded the JSON so it looks like this:
{"questions":[
{"id":214,"prompt":"Is this a question?"} //--added manually--//
],
"quizzes":[{"id":185,"title":"First Quiz","questions":[214]},
{"id":186,"title":"Second Quiz","questions":[]},
{"id":187,"title":"Third Quiz","questions":[]},
...
...
]}
Here is a pattern I've seen a couple times in my search for an answer:
Ember QuestionsNewController:
Quizzmob.QuestionsNewController = Ember.ArrayController.extend(
needs: 'quiz'
quiz: Ember.computed.alias('controllers.quiz.model')
prompt: ''
actions:
save: ->
quiz = #get('controllers.quiz.content')
quiz.save()
prompt = #get('prompt')
question = #store.createRecord "question",
prompt: prompt
#set('prompt', '')
questions = quiz.get('questions')
questions.addObject(question)
question.save().then =>
quiz.save()
)
My console shows all successful calls, my server shows successes too:
Processing by Api::V1::QuestionsController#create as JSON
Parameters: {"question"=>{"prompt"=>"new", "quiz_id"=>"185"}}
Completed 200 OK
Processing by Api::V1::QuizzesController#update as JSON
Parameters: {"quiz"=>{"title"=>"First Quiz"}, "id"=>"185"}
Completed 200 OK
A new Model for Question gets created and I see it in my Ember Debugger, but when I refresh the page, the model disappears. I read somewhere that it may have something to do with my serializer, and that I might have to add a 'serializeHasMany' method to customize it...but that seems like a lot of work for a seemingly simple and common task. Not sure if it's the 'ember way'.
Thanks so much for any help. I'll update the question with any additional info that's needed.
I have a similar type of relationship in my database, and I think I see what your problem is. With ember, the relationship is not going to be saved on the hasMany side. So the relationship will be completely defined in your database in the questions table. To find all questions a quiz has, you would have to filter the database based on the paramter that the
{quiz_id: SOME_ID}
Now a question to ask yourself is can the questions on be on one quiz? If they can be on many quizzes, then you have a manyToMany relationship, which would probably require a change to the serializer, as I had to make myself.
In conclusion, the reason that your list of questions isn't being updated or sent to the server, is because you can only add the relationship to the Question itself, so question.set('quiz', some_quiz). You cannot get all questions from the quiz.
I hope this helps, sorry for all the wording.

Rails 4 Add Parameters to New Record Creation

I am having trouble getting a parameter to show up as an additional param when I create a new item.
Conceptually I have 3 models, Tickets, Issues and a join table IssueTickets.
Tickets have many issues through IssueTickets
Issues have many tickets through IssueTickets
A user can create a ticket from an issue. When they click the new ticket button i'm trying to get the id of it to go through so that I can associate it in the join table and do some custom alerting.
issues/show.html.erb
<%= link_to "Create Ticket", new_ticket_path(:issues => #issue.id), :class => 'btn' %>
The ID shows up in the URI, however i don't have access to it when the request goes through. I suspect that it is related to strong parameters in my ticket controller.
def ticket_params
params.require(:ticket).permit(:title, :description, :status, :priority, :latitude, :longitude, :issues)
params.permit(:issues)
end
So, what am i doing wrong, and is their a better way to do this? I was thinking accepts nested parameters, but all i am doing is creating the association between the ticket and issue and then alerting the associated users (both the issue owner and the dispatcher of the tickets)
Alright so was making a silly mistake, hope this helps someone else in the future.
I was permitting this in the strong parameters but wasn't assigning anything in the new action. After handling the parameter in the new action so that the create action saw it everything worked just fine.

Get profile picture from Facebook using social-auth

I am implementing social login in my application and I am already getting normal fields as First Name, Last Name on Facebook and LinkedIn... Now I want to get the profile picture. I did it for LinkedIn and it is working perfectly, i can see the URL on the extra fields from the database.
I am trying to do the same with Facebook, as I saw here https://groups.google.com/forum/?fromgroups#!topic/django-social-auth/Mee8H8HhLQk
defining
FACEBOOK_PROFILE_EXTRA_PARAMS = {'fields': 'picture'}
FACEBOOK_EXTRA_DATA = [('profile', 'profile')]
But when i did this, somethings got messed up. I am not able anymore to get the first name and last name in my user table as I was doing before these two lines of code. Does anyone know why this problem is happening?
The picture is under http://graph.facebook.com/<user_id>/picture. The user_id is given by the FacebookBackend.

Extending django-registration fields

I am trying to extend the fields in django-reg (with First name, last name and contact number). To this end, I have written an app (name=regfields), with the following contents:
http://dpaste.com/596163/
When I run syncdb, I see all the extra fields I have set up on the database, but, when I try and create an account, the extra fields I have given are not stored in my database.
What could be wrong?
Sorry, I am a django 101 user!
The indentation of the save() function in newforms.py looks off. Assuming that is not an error introduced by copying it into dpaste, that method is not a part of RegistrationFormZ.