active admin strong parameters failing - html

I am trying to create a record in active admin. My activeadmin is set up with this:
ActiveAdmin.register MyObject do
permit_params :all_my_params, :client_id
end
The form should be submitting the params as such:
{"utf8"=>"✓", "authenticity_token"=>"WnStZr//M1rBDSwNWSrZs2rvCmcpji/MKaLywxuf9oG0Ef3b1uojy5jszs3yHEYmpvjt+qtJrmi3jz3KKJgUCQ==", "MyObject"=>{"client_id"=>"1", "all_my_params"=>"something here"}, "commit"=>"Create My Object"}
However, the form submits with an extra client_id outside of the MyObject hash like so:
{"utf8"=>"✓", "authenticity_token"=>"WnStZr//M1rBDSwNWSrZs2rvCmcpji/MKaLywxuf9oG0Ef3b1uojy5jszs3yHEYmpvjt+qtJrmi3jz3KKJgUCQ==", "MyObject"=>{"client_id"=>"1", "all_my_params"=>"something here"}, "commit"=>"Create My Object", "client_id"=>"1"}
(notice the extra client_id)
This gives me an error:
unpermitted parameter: client_id
because it is not expected outside my MyObject hash.
How can I fix this? I've been stuck on this for days!
My relevant routes: batch_action_admin_client_wedding_cakes POST /admin/clients/:client_id/wedding_cakes/batch_action(.:format) admin/wedding_cakes#batch_action
admin_client_wedding_cakes GET /admin/clients/:client_id/wedding_cakes(.:format) admin/wedding_cakes#index
POST /admin/clients/:client_id/wedding_cakes(.:format) admin/wedding_cakes#create
new_admin_client_wedding_cake GET /admin/clients/:client_id/wedding_cakes/new(.:format) admin/wedding_cakes#new
edit_admin_client_wedding_cake GET /admin/clients/:client_id/wedding_cakes/:id/edit(.:format) admin/wedding_cakes#edit
admin_client_wedding_cake GET /admin/clients/:client_id/wedding_cakes/:id(.:format) admin/wedding_cakes#show
where wedding_cake = MyObject in my previous code.
In essence, the client_id that is parsed from the url automatically which would normally be accepted in a rails controller is not getting accepted in activeadmin and I have no way of making it permitted since I can only permit things that are inside the wedding cakes hash in my params.

Related

Lua Roblox HttpService:PostAsync Stripping Json

I'm trying to validate against an external API that uses hashing against the body + API.
In Roblox I have:
body = '{"attributes":[{"name":"player_level","value":120},{"name":"is_whale","value":true,"data_type":"boolean"}]}'
Which I then call this:
local attributeData = game.HttpService:PostAsync(encoded_url,body,Enum.HttpContentType.ApplicationJson,false,headers)
But in my logs:
19 Aug 2022 20:44:34.8862022-08-19 20:44:34 +0000 severity=INFO, method=POST path=/api/v1/appuser/toms_awesome_rblx_guy1/attributes format=json controller=Api::V1::Appuser::AttributesController action=create status=0 duration=1.09 view=0.00 db=0.00 ip= attributes=[{"name"=>"player_level", "value"=>120}, {"name"=>"is_whale", "value"=>true, "data_type"=>"boolean"}] session_id=62f52645795301001985e2d7 enc=0fea853f09e361b9d80579d99acda0a69c8e3c7045a2834d30b03e650a5d5f86 appuser_external_id=toms_awesome_rblx_guy1
Notice how the {}'s were stripped off to become this: attributes=[{"name"=>"player_level", "value"=>120}, {"name"=>"is_whale", "value"=>true, "data_type"=>"boolean"}]
This is ultimately causing issues with validation because the hash was made on my end with the {}'s.
Any ideas where I'm going wrong? I've tried different combinations of Enum.HttpContentType.ApplicationUrlEncoded and "data="..body and encoded_body = game.HttpService:JSONEncode(body)
But they all seem to append things in front of the generated json in the logs like data= or _json=. None of which were in my original hash based on the body json string I wouldn't expect to change.

Laravel, delete a queue job by user id

Each time a user is created or updated, an email will be send when some timestamp is reached.
I control this by queues. Each queue is stored in the "jobs" table.
That table has a column called "payload" which is a json with all the info of that job. In my case, a payload of this is like this one:
{
"job":"Illuminate\\Queue\\CallQueuedHandler#call",
"data":{
"commandName":"Illuminate\\Mail\\SendQueuedMailable",
"command":"O:34:\"Illuminate\\Mail\\SendQueuedMailable\":1:{s:11:\"\u0000*\u0000mailable\";O:16:\"App\\Mail\\Expired\":16:{s:7:\"\u0000*\u0000user\";O:45:\"Illuminate\\Contracts\\Database\\ModelIdentifier\":2:{s:5:\"class\";s:8:\"App\\User\";s:2:\"id\";i:1020;}s:4:\"from\";a:0:{}s:2:\"to\";a:1:{i:0;a:2:{s:7:\"address\";s:24:\" example#gmail.com\"\";s:4:\"name\";N;}}s:2:\"cc\";a:0:{}s:3:\"bcc\";a:0:{}s:7:\"replyTo\";a:0:{}s:7:\"subject\";N;s:4:\"view\";N;s:8:\"textView\";N;s:8:\"viewData\";a:0:{}s:11:\"attachments\";a:0:{}s:14:\"rawAttachments\";a:0:{}s:9:\"callbacks\";a:0:{}s:10:\"connection\";N;s:5:\"queue\";N;s:5:\"delay\";N;}}"
}
}
As you can see, there job is associated with: App\\User\";s:2:\"id\";i:1020
How could I remove that job from the table, by that user id? I could get all the data with DB::table('jobs) and loop until I found the id inside payload and delete it, but is there any helper or function of Laravel to do that?
You can json_decode the payload and unserialize the $payload['data']['command']
$job = DB::table('jobs')->whereId($id)->first();
$payload = json_decode($job->payload);
$mailable = unserialize($payload['data']['command']);
if ($mailable->user->id != GOOD)
DB::table('jobs')->whereId($id)->delete();
hope this helps

Using Ruby, grab value from HTML string inside a JSON response

I have searched what I can and I don't seem to be finding the answer I need. Granted I may not be wording it properly. I have tried using .find or even .rindex to count backwards, but no such luck. The value I receive from the JSON looks something like this:
"AdditionalData":"<Data><Entry Key=\"utm_campaign\" Value=\"j2c\" />
<Entry Key=\"utm_medium\" Value=\"cpc\" /><Entry Key=\"utm_source\"
Value=\"j2c\" /><Entry Key=\"job_id\" Value=\"300_xxxx_10703\" /></Data>"
I need to be able to grab the value for the key "job_id", so the "300_xxxx_11233". This value will change per object returned by the JSON response. Any help would be appreciated, and please let me know if this is already out there and I just missed it.
If the response format remains the same with every request, you could use a plain regexp expression to fetch your data, even without parsing JSON. Example:
response = "<Data><Entry Key=\"utm_campaign\" Value=\"j2c\" /><Entry Key=\"utm_medium\" Value=\"cpc\" /><Entry Key=\"utm_source\" Value=\"j2c\" /><Entry Key=\"job_id\" Value=\"300_xxxx_10703\" /></Data>"
match = response.match(%r{job_id\\?"\s+Value=\\?"(.+)\\?"}i)
match[1] if match # => "300_xxxx_10703"
If the response format can change (for example, if the order of the attributes of Entry element can change), then you need to parse JSON and use some HTML parser, such as Nokigiri, to fetch required attrbute. Code example:
parsed_response = JSON.parse(response)
doc = Nokogiri::HTML(parsed_response['AdditionalData'])
job_id = nil
doc.css('Entry').each do |el|
if el['Key'] == 'job_id'
job_id = el['Value']
break
end
end

reHow to send a set of string in single variable through url

I want to send a value in URL that value contains more than one words i am using the given concept for example
<a href=page.jsp?variable1=value1&variable2=value2>click here</a>
Suppose in above value value1=aa and value2=bb cc dd
but in the url of page.jsp i am getting value1=aa and value2=bb only and the rest value "cc dd" is missing.
what should i do to get complete value for example value2=bb cc dd
I am giving here my code after making it more simple to focus on desire problem
`<%
MongoClient mongo = new MongoClient("localhost",27017);
DB database = mongo.getDB("studentDB");
DBCollection collection = database.getCollection("AskQuestion");
DBCursor cursor = collection.find();
String bodycontent="";
while(cursor.hasNext())
{
DBObject str=cursor.next();
bodycontent+="<table><tr><td><div> "+ str.get("TITLE") +"</div></td></tr></table>";
}
out.print(bodycontent);
%>`
For example str.get("_id") gives value "55093da9223da86a0212b364" and
str.get("TITLE") gives value "Question Title" .
Now my problem is i got value in Answer.jsp for str.get("TITLE") is only "Question" but not "Title" and i want the full value i.e Question Title.
I hope i am clear with my problem.
Try encoding your second variable and then attach it.
example: bb%20cc%20dd
<a href=page.jsp?variable1=value1&variable2=bb%20cc%20dd>click here</a>
You need to use java script for encoding your URL see this question for more details.
Passing a URL as a GET parameter in Javascript
Edit
See these answers
How to URL encode a URL in JSP?
http://www.coderanch.com/t/521213/JSP/java/encoding-URL-href-element-JSP

Ember many-to-many Ids are not included in JSON payload on post?

I have a meeting and a sales-rep models, The relation is ManyToMany.
The problem is, When I want to create a New meeting, and assign existing salesReps to it (They are already saved to the store), But The salesReps IDS are not included in The post action caused by model.save() (not even an empty array), To make it more clear, Here is what my code looks like:
meeting.coffee:
Meeting = DS.Model.extend
client: DS.belongsTo('client')
salesReps: DS.hasMany('sales-rep')
memo: DS.attr('string')
startDate: DS.attr('date')
duration: DS.attr()
sales-rep.coffee:
SalesRep = DS.Model.extend
meetings: DS.hasMany('meeting')
firstName: DS.attr('string')
lastName: DS.attr('string')
title: DS.attr('string')
meetings/new.coffee (the save action am using inside new meeting controller):
save: ->
meeting = #get('model')
meeting.set('client', #get('client'))
meeting.get('salesReps').pushObjects(#get('salesReps.content'))
meeting.save().then =>
#transitionToRoute 'meetings'
the JSON payload: ( POST http://localhost:4200/api/meetings)
meeting: {memo: null, start_date: null, duration: "00:15", client_id: null}
client_id: null
duration: "00:15"
memo: null
start_date: null
No matter what, There is no ANY trace of the salesReps ids in the payload!!
What I tried so far:
Setting the hasMany relation in the meeting model only.
Setting {async: true}, and then {async: false}, on both SalesRep, And
then on one of them
spending almost 2 days googling and reading all related posts in here
with no luck
Any Help/hints/Advice, Is highly appreciated
I will write the solution I found after endless reading and researching, I will write the full details, and trial/failure i've been through, Because no one, no one EVER should have to spend more than 3 days trying to fix something like that!!
I am using Ember-cli, So, there are a files/directories structure am following:
First attempt:
Trying all combinations of async: true, embedded true and what not.
Result, No luck
Second attempt:
in app/serializers/ I added the following serializer file:
meeting.coffee
`import DS from "ember-data"`
`import Ember from "ember"`
`import config from '../config/environment'`
get = Ember.get
serializer = DS.RESTSerializer.extend
serializeHasMany: (record, json, relationship) ->
rel_ids = get(record, relationship.key).map (rel) -> get(rel, 'id') || []
json["#{relationship.key.underscore().singularize()}_ids"] = rel_ids
json
`export default serializer`
result:
Adding this serializer, And I finally was able to send sales_rep_ids:[] array to the controller! and I could confirm that the server is saving the accociations as required.
But, When listing meetings, I was not able to list the associated salesReps, So, I checked the JSON am getting from the server, and it was correct (salesReps Ids were included!) But still not listed in Ember
Third Attempt:
After more reading and endless head-banging-against-the-wall, Changing ONE line fixed the problem!:
in app/serializers/meeting.coffee
change serializer = DS.RESTSerializer.extend to
serializer = DS.ActiveModelSerializer.extend
And Voila! Saved to the back-end, And listed correctley as association in ember!
This solution is a result of 3+ of constant headache, Am posting it here hopefully it might be helpful to someone facing the same problem, I can't claim that it's my own solution, but, It's the result of reading many people's code.
am not sure if it's the Ember way to do so, So, Any suggestions, Improvements Ideas and thought are welcome.