semicolon as statement separator in Rails Console - ruby-on-rails

The Rails console doesn't seem to like multiple ruby statements on the same line separated by a semicolon. Whenever I do this, the next line starts with ?> and I find that only the first statement was executed. Do you have to put each statement on a separate line?
>> user = User.new
user = User.new
=> #<User id: nil, username: "", hashed_password: "", first_name: "", last_name: "", email: "", display_name: "", user_level: 0, created_at: nil, updated_at: nil, posts_count: 0>
>> user.username = "John"; hashed_password = "John"; first_name = "John"; last_name = "coltrane"; email = "John#coltrane.com"; display_name = "Johndispay"; user_level = 9;
user.username = "John"; hashed_password = "John"; first_name = "John"; last_name = "coltrane"; email = "John#coltrane.com"; display_name = "Johndispay"; user_level = 9;
?> user.save
user.save
=> true
Everything except user.username = "John"; was ignored

You need to say "user." so Ruby knows you mean to call the attribute assignment methods of the instance of user. Otherwise, you are just setting local variables called "hashed_password", etc.
>> user.username = "John"; user.hashed_password = "John"; user.first_name = "John"; user.last_name = "coltrane"; user.email = "John#coltrane.com"; user.display_name = "Johndispay"; user.user_level = 9;
Although, you could just pass a hash of the attributes you want to set on the new instance, like so
>> user = User.new(:username => "John", :hashed_password => "John", ...

It's the trailing ; on your input. When you put a ';' on the end IRB will assume you want to add another statement. If you leave it off, it will evaluate all the statements and return the return value of the last one.
Sometimes if the method I'm calling is going to return a large array I will do something like this...
a = Account.entries; a.size
This will save the values I need and just output the size of the array instead of trying to dump it to the console, which can take a long time if it's large.

are you sure you didn't mean
user.username = "John"; user.hashed_password = "John";
i tried
>> a = 1; b= 2
=> 2
>> a
=> 1
>> b
=> 2
when something doesn't work, you can use one rule: always reduce it to the simplest case.

Related

wrong number of arguments (given 0, expected 1) when calling update_attributes

I have a method that is called every time the user signs in to my app using facebook or gplus, where I update all the user fields on each sign in.
user = where(:email => email).first_or_create do |user|
user.uid = uid
user.email = email
user.provider = provider
user.save!
end
user.first_name = auth["first_name"]
user.last_name = auth["last_name"]
user.nickname = auth["first_name"]
user.name = auth["name"]
user.gender = auth["gender"]
user.role = "user"
user.latitude = 0
user.longitude = 0
user.update_attributes(user.attributes)
user
but i get the following error everytime this method is called, in a similar note, I get this error even when I try updating a single attribute
user.upate_attributes(:token => token)
wrong number of arguments (given 0, expected 1)
can't seem to figure out why
Why don't you just save the user instance
# ...
user.longitude = 0
user.save
or try this way
user.update_attributes(
first_name: auth["first_name"],
last_name: auth["last_name"],
nickname: auth["first_name"],
name: auth["name"],
gender: auth["gender"],
role: "user",
latitude: 0,
longitude: 0
)
Also, In your second command, there is a typo
user.upate_attributes(:token => token)
# Change to
user.update_attributes(:token => token)

Add fields to model without permit param

am trying to add fields to a model directly from the controller action without a form,only the user_id is saved the other columns (firstname,lastname) are empty each time i run the code, below is the code, note: User has_many :provide_helps.
#firstname=current_user.firstname
#lastname=current_user.lastname
#gh_user = User.find_by status: 'gh'
#ph = #gh_user.provide_helps.create(firstname: "#{#firstname}" , lastname: "#
{#lastname}")
Try this
#ph = #gh_user.provide_helps.create(firstname: #firstname , lastname: #lastname)
No need to assign #first_name and #last_name using #{}.
you can use the code below:
#gh_user = User.find_by(status: 'gh')
#ph = #gh_user.provide_helps.new({ firstname: current_user.firstname, lastname: current_user.lastname })
#ph.save
or
#gh_user = User.find_by(status: 'gh')
#ph = #gh_user.provide_helps.new()
#ph.first_name = current_user.first_name
#ph.last_name = current_user.last_name
#ph.save

Rails 4.2: Rake Task to Import CSV Issue

I have a rake task that should import a .csv file and save the data into the database. So far it runs but when I check the database - nothing was saved and I see no errors - leaving me with no direction.
I'm using Rails 4.2 with Postgresql for the db.
Here is my task..
namespace :import_users do
desc "imports user data from a csv file"
task :data => :environment do
require 'csv'
CSV.foreach('/Users/RAILS/Extra Files/2015 User Report.csv') do |row|
plan = row[0]
contact_ident = row[1]
prefer_fax = row[2]
pin = row[3]
name = row[4] #account
first_name = row[5]
last_name = row[6]
email = row[7]
phone = row[8]
prefer_fax == "Yes" ? p_fax = true : p_fax = false
p = Plan.where("name ~ ?","#{plan}( )")
user = User.create( contact_ident: contact_ident,
prefer_fax: p_fax,
first_name: first_name,
last_name: last_name,
email: email
)
account = Account.where("pin ~ ?", "#{pin}").first_or_create do |account|
account.name = name
account.phone = phone
end
user.plans << p
user.accounts << account
end
end
end
Can you try to replace
User.create
with
User.create!
so if there is any problem with creation it raise.

grails hql left outer join

how is it possible to left outer join 2 tables?
class Person {
String firstName
String lastName
String gender
//static hasMany = [votes: Vote]
static mapping = {
version false
}
static constrains = {
}
}
class Vote {
Person voter;
Person subject;
static mapping = {
version false
}
static constraints = {
voter nullable: false
subject nullable: false
}
}
i need to get every person thats not subjected to a vote, for a specific person.
lets say person 1 votes for 3 out of 5 persons, i need the other 2 that he didnt vote for to show up for him.
How is the query supposed to be?
EDIT:
def personInstance1 = new Person(firstName: "Antonio", lastName: "Vivaldi", gender: "m")
def personInstance2 = new Person(firstName: "Dennis", lastName: "Rodman", gender: "m")
def personInstance3 = new Person(firstName: "Marc", lastName: "Oh", gender: "m")
def personInstance4 = new Person(firstName: "Gudrun", lastName: "Graublume", gender: "w")
def personInstance5 = new Person(firstName: "Hilde", lastName: "Feuerhorn", gender: "w")
def personInstance6 = new Person(firstName: "Mandy", lastName: "Muller", gender: "w")
personInstance1.save()
personInstance2.save()
personInstance3.save()
personInstance4.save()
personInstance5.save()
personInstance6.save()
def voteInstance1 = new Vote(voter: personInstance1, subject: personInstance2)
def voteInstance2 = new Vote(voter: personInstance1, subject: personInstance3)
def voteInstance3 = new Vote(voter: personInstance1, subject: personInstance4)
def voteInstance4 = new Vote(voter: personInstance1, subject: personInstance5)
def voteInstance5 = new Vote(voter: personInstance2, subject: personInstance1)
voteInstance1.save()
voteInstance2.save()
voteInstance3.save()
voteInstance4.save()
voteInstance5.save()
this is my grails bootstrap-file , Antonio and Dennis have voted, and each need to be presented a list of people they didnt vote for.
EDIT:
this way i seem to get a result for Dennis, since he only voted once,
but if i put v.voter_id = 1,
to get a result for Antonio, the result doubles according to how many votes he did.
SELECT first_name FROM vote as v
LEFT OUTER JOIN person as p
ON v.subject_id != p.id AND v.voter_id = 2
WHERE p.id IS NOT NULL
Try this:
SELECT * FROM Person P
WHERE NOT EXISTS(
SELECT 'Vote' FROM Vote V
WHERE V.subject = P
)
In this way you'll extract all Person without Vote
EDIT
In SQL you can retrieve a matrix in this way:
CREATE TABLE #person (nome varchar(30))
CREATE TABLE #vote (votante varchar(30), candidato varchar(30))
INSERT INTO #person values
('Antonio Vivaldi'),
('Dennis Rodman'),
('Marc Oh'),
('Gudrun Graublume'),
('Hilde Feuerhorn'),
('Mandy Muller')
INSERT INTO #vote values
('Antonio Vivaldi', 'Dennis Rodman'),
('Antonio Vivaldi', 'Marc Oh'),
('Antonio Vivaldi', 'Gudrun Graublume'),
('Antonio Vivaldi', 'Hilde Feuerhorn'),
('Dennis Rodman', 'Antonio Vivaldi')
SELECT *
FROM #person p
CROSS JOIN #person c
WHERE NOT EXISTS(
SELECT 'X'
FROM #vote v
WHERE v.votante = p.nome
AND v.candidato = c.nome
)
AND p.nome <> c.nome
ORDER BY p.nome

Ruby on Rails: Updating data problems

Okay so I'm just trying to write some simple code that updates a record given an ID. This is what it looks like.
def updaterecord
bathroom = Bathroom.find(params[:key])
bathroom.name= params[:name],
#bathroom.bathroomtype = params[:bathroomtype],
bathroom.street = params[:street]
#bathroom.city = params[:city],
#bathroom.state = params[:state],
#bathroom.country = params[:country],
#bathroom.postal = params[:postal],
#bathroom.access = params[:access],
#bathroom.directions = params[:directions],
#bathroom.comment = params[:commment],
#bathroom.avail = params[:avail]
bathroom.save
end
The problem is that although I am trying to update each individual attribute they are all getting concatenated to the name field. For example, this code above sets the name field to the name plus the address. I don't know why?
This is what the console looks like if I try to query after doing the update.
Bathroom Load (0.2ms) SELECT "bathrooms".* FROM "bathrooms" WHERE "bathrooms"."ID" = ? LIMIT 1 [["ID", 4017]]
=> #<Bathroom ID: 4017, name: "--- \n- ttyt\n- 113 some\n", bathroomtype: "0", street: "113 some", city: "Portland", state: "OR", country: "United States", postal: "97217", lat: #<BigDecimal:1109f2890,'0.4558056E2',12(12)>, lon: #<BigDecimal:1109f27c8,'-0.122677857E3',12(16)>, access: "0", directions: "", comment: nil, created: "2012-06-08 17:19:03.420329", modifed: "", avail: "1", slug: "", source: "Squat">
And this is what the post values look like:
post values = key=4017&name=www&bathroomtype=0&street=7540 N Interstate Ave&city=Portland&state=OR&country=United States&postal=97217&access=0&directions=&comment=<null>&avail=1
Why can't I get each field to update individually? Sorry I'm confused as to what is going on?
I think you might an unnecessary comma there at the end of the line.
It should just read:
def updaterecord
bathroom = Bathroom.find(params[:key])
bathroom.name= params[:name]
bathroom.street = params[:street]
bathroom.save
end
it doesn't look like you have correctly urlencoded your post values
a simple
puts params.inspect
or
pp params
should log out the params object. You can also use
render :text => params.inspect
to print it out to your result html

Resources