Add fields to model without permit param - ruby-on-rails

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

Related

creating multiple records with a single JSON post

The following parameters are being posted
Parameters: {
"orig_id"=>47,
"terms_accepted"=>true,
"email"=>"sod#gos.co",
"name"=>"firstname",
"surname"=>"surname",
"kids"=>[
{"school"=>"Faraway", "rate"=> "89"},
{"school"=>"Transfer", "rate"=> "23"},
{"school"=>"Bike", "rate"=>"4"}]
}
However, the rails controller action, defined as follows only creates the parent record, but not the related ones:
parent = params[:parent]
#parent = Parent.new(orig_id: parent['orig_id'], terms_accepted: parent['terms_accepted'], email: parent['email'], name: parent['name'], surname: parent['surname'])
#parent.save
kids = params[:kids]
kids each do |kid|
#kid = Kid.new(school: kid['school'], rate: kid['rate'], parent_id: #parent.id)
#kid.save
end
where is the syntax wrong?
kids each do |kid| actually should be kids.each do |kid|.

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

Conditionally add OR condition in query

The orders table have a few columns, say email, tel and address.
User provides email/tel/address, and any of them can be nil or empty string (EDITED).
How to generate an OR query, so if any of the columns match, the record is returned?
The only catch is that if any value provided is nil or empty, that will be ignored instead.
I was able to do the following using Arel:
email = params[:email]
tel = params[:tel]
address = params[:address]
t = Order.arel_table
sq = t[:email].eq(email) if email.present?
sq = sq.or(t[:phone].eq(phone)) if phone.present?
sq = sq.or(t[:phone].eq(address)) if address.present?
Order.where( sq )
However it will err if email is nil, because sq will not instantiate.
I want to prevent constructing sql string, and I use Squeel gem.
you can put
Order.where("email=? or tel= ? or address=?", params[:email], params[:tel], params[:address])
You can check whether your params are nil or not by Ick's maybe. So read about Ick gem and follow the steps given there and then you can use it in your case like :
params[:email].maybe
params[:tel].maybe
params[:address].maybe
Hope, this is what you were looking for.
Please have a try with
where_condition = "true"
where_condition += "OR email = '#{params[:email]}'" if params[:email].present?
where_condition += "OR tel = '#{params[:tel]}'" if params[:tel].present?
where_condition += "OR address = '#{params[:address]}'" if params[:address].present?
Order.where(where_condition)
In order to prevent nil or empty string, I finally got the following:
t = Order.arel_table
conditions = [:email, :phone, :address].map{|attr|
attr_value = params[attr]
if attr_value.present?
t[attr].eq(attr_value)
else
nil
end
}.compact
if conditions.empty?
Order.where('1=0')
else
Order.where( conditions.inject{|c, cc| c.or(cc).expr} )
end
Ugly, but flexible.

Create model instance if title is blank (null)?

In my Rails app users can create submissions, and each submission has a title and content. Right now in the create action of of my submissions controller, it'll check to see if there are any submissions in the database that match the title of the new submission being created. If there is one in the db with the same title, it will update the one already in the db instead of creating another.
I'd like to continue to do that, however, if the value of the :title attribute is NULL (aka they didn't enter anything), I'd like it to go ahead and create a new instance REGARDLESS of if there's another instance in the db with the :title value of NULL.
Here's my attempt, which doesn't work:
def create
ajax_title = params[:title]
ajax_content = params[:content]
ajax_folder = params[:folder_id]
ajax_parent = params[:parent_id]
ajax_children = Array(params[:children])
#submissions = Submission.where(title: ajax_title)
if #submissions.empty?
#submission = Submission.create({title: ajax_title, content: ajax_content, user_id: current_user.id, folder_id: ajax_folder, parent_id: ajax_parent, children: ajax_children})
else
if #submissions.blank?
#submission = Submission.create({title: ajax_title, content: ajax_content, user_id: current_user.id, folder_id: ajax_folder, parent_id: ajax_parent, children: ajax_children})
else
#submissions[0].content = ajax_content
#submissions[0].save
end
end
end
How do I check and ensure that submission instances with a :title value of NULL are each created and not updating another previous one with the same title value?
This should do it:
ajax_title = params[:title]
ajax_content = params[:content]
ajax_folder = params[:folder_id]
ajax_parent = params[:parent_id]
ajax_children = Array(params[:children])
#submission = Submission.find_by_title(ajax_title)
if ajax_title && #submission
#submission.content = ajax_content
#submission.save
else
#submission = Submission.create(
:title=>ajax_title,
:content=>ajax_content,
:user_id=>current_user.id,
:folder_id=>ajax_folder,
:parent_id=>ajax_parent,
:children=>ajax_children,
)
end

semicolon as statement separator in Rails Console

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.

Resources