I used to code below to deserialize the JSON API data send from client,
def action_record_params
ActiveModelSerializers::Deserialization.jsonapi_parse!(params)
end
When I pass the following data from the client, the deserializer cannot see relationships attributes.
Client send parameter
params = {"data": {"type": "action_record", "attributes": {"value": ""}}, "relationships": {"card": {"data": {"type": "card", "id": "#{card.id}"}}}}
Server deserialized data
{:value=>""}
How to deserialize parameters with relationships using ActiveModelSerializers?
Base on AMS documentation Deserialization section, which can be found below
https://github.com/rails-api/active_model_serializers/blob/master/docs/general/deserialization.md
The relationships can be extracted by via the option only: [:relatedModelName]. only is act as a whitelist in this case.
Sample Data
document = {
'data' => {
'id' => 1,
'type' => 'post',
'attributes' => {
'title' => 'Title 1',
'date' => '2015-12-20'
},
'relationships' => {
'author' => {
'data' => {
'type' => 'user',
'id' => '2'
}
},
'second_author' => {
'data' => nil
},
'comments' => {
'data' => [{
'type' => 'comment',
'id' => '3'
},{
'type' => 'comment',
'id' => '4'
}]
}
}
}
}
AMS deserialization with options
ActiveModelSerializers::Deserialization
.jsonapi_parse(document, only: [:title, :date, :author],
keys: { date: :published_at },
polymorphic: [:author])
Output hash
# {
# title: 'Title 1',
# published_at: '2015-12-20',
# author_id: '2',
# author_type: 'user'
# }
Related
According to this answer, its possible to append data to JSON.
But when I try test.push I get the error NoMethodError: undefined method push' `.
NETWORK_SG = Azure::Armrest::Network::NetworkSecurityGroupService.new(conf)
network_sg = NETWORK_SG.get('testing_123', rg)
test = network_sg.properties
puts test
{
"provisioningState": "Succeeded",
"resourceGuid": "test",
"securityRules": [
{
"name": "SSH",
"id": "SSH",
"etag": "18",
"type": "Microsoft/securityRules",
"properties": {}
}
]
}
options = {"key": "value"}
test.push(options)
How can I append the following JSON data to securityRules[]? Sometimes securityRules[] can be a empty array but I still want to append.
{
:name => 'rule_2',
:properties => {
:protocol => 'TCP',
:sourceAddressPrefix => '*',
:destinationAddressPrefix => '*',
:access => 'Allow',
:destinationPortRange => '22',
:sourcePortRange => '*',
:priority => '301',
:direction => 'Inbound',
}
}
You can use Array#push like this:
test = {
:provisioningState=>"Succeeded",
:resourceGuid=>"test",
:securityRules=>[
{:name=>"SSH", :id=>"SSH", :etag=>"18",:type=>"Microsoft/securityRules", :properties=>{}}
]
}
new_rule = {
:name => 'rule_2',
:properties => {
:protocol => 'TCP',
:sourceAddressPrefix => '*',
:destinationAddressPrefix => '*',
:access => 'Allow',
:destinationPortRange => '22',
:sourcePortRange => '*',
:priority => '301',
:direction => 'Inbound',
}
}
test[:securityRules].push(new_rule)
test
# {
# :provisioningState=>"Succeeded",
# :resourceGuid=>"test",
# :securityRules=> [
# {:name=>"SSH", :id=>"SSH", :etag=>"18", :type=>"Microsoft/securityRules", :properties=>{}},
# {:name=>"rule_2",:properties=>{:protocol=>"TCP",:sourceAddressPrefix=>"*",:destinationAddressPrefix=>"*",:access=>"Allow",:destinationPortRange=>"22",:sourcePortRange=>"*",:priori# ty=>"301",:direction=>"Inbound"}}
# ]
# }
Acccording to https://github.com/sumoheavy/jira-ruby rails gem I have to setup a valid jira user and api password to allow me access Jira api.
I can create issue according to the follow code but when I see the record logs or even in the Jira page the Reporter title goes with my username. I need to create the Issue username "reporter" from my html input form which I don't know what my user will type...
So how can I create an Issue with custom usernames user Rails Jira gem?
According to their test suite:
JIRA::Resource::Issue.new(client, attrs: {
'id' => '123',
'fields' => {
'reporter' => { 'foo' => 'bar' },
'assignee' => { 'foo' => 'bar' },
'project' => { 'foo' => 'bar' },
'priority' => { 'foo' => 'bar' },
'issuetype' => { 'foo' => 'bar' },
'status' => { 'foo' => 'bar' },
'components' => [{ 'foo' => 'bar' }, { 'baz' => 'flum' }],
'versions' => [{ 'foo' => 'bar' }, { 'baz' => 'flum' }],
'comment' => { 'comments' => [{ 'foo' => 'bar' }, { 'baz' => 'flum' }] },
'attachment' => [{ 'foo' => 'bar' }, { 'baz' => 'flum' }],
'worklog' => { 'worklogs' => [{ 'foo' => 'bar' }, { 'baz' => 'flum' }] }
}
})
end
Which means you should be able to write:
issue = client.Issue.build
issue.save({"fields"=>{"reporter"=> {"username" => "reporter"},"summary" => {"Crazy froggy"}}
I'm guessing as to "username" being the appropriate key here - but if they're calling this in a spec, then you should be able to call it in your code.
Now the problem may be that "reporter" isn't a valid user within Jira - because their spec tests:
it 'has the correct relationships' do
expect(subject).to have_one(:reporter, JIRA::Resource::User)
expect(subject.reporter.foo).to eq('bar')
The expect(subject).to have_one(:reporter, JIRA::Resource::User) line suggests that the 'reporter' value has to be a valid instance of JIRA::Resource::User which tells me that you cannot set this field to whatever you want. I think that JIRA charges based on how many accounts you have for your JIRA instance? So each User would be a separate license.
I'm doing a lot of guesswork here - but I think this means you need to pay to license the 'reporter' User within JIRA, and then you could set it for all these issues.
I am trying to stub a post request with the below response
{ 'data' => {
'detections' =>
[
[{
'language' => 'en',
'isReliable' => false,
'confidence' => 0.134
}],
[{
'language' => 'ar',
'isReliable' => false,
'confidence' => 0.9882
}]
]
} }
Can anyone help
You can use webmock https://github.com/bblimke/webmock#stubbing-requests-based-on-method-uri-body-and-headers
response = { 'data' => {'detections' =>[[{'language' => 'en','isReliable'=>false,'confidence' => 0.134}],[{'language' => 'ar','isReliable' => false,'confidence' => 0.9882 }]]}}
stub_request(:post, "url").with(<if needed>).to_return(status: 201, body: response.to_json, headers: { 'Content-Type' => 'application/json'})
I try to get POST Variables in my controller from view with:
<?= GridView::widget([
'dataProvider' => $dataProvider_products,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label'=>'Name',
'format' => 'raw',
'value'=>function ($data) use ($model, $dataProvider_products) {
return Html::a($data['name'],['suppliers_orders/addproduct', 'order' => $model->id, 'product' => $data['id'],
'data-method'=> 'post',
'data-params' => ['dataProvider' => $dataProvider_products],
]);
},
],
'supplier_product_number',
'size',
'price_net',
],
]); ?>
The parameter dataProvider will always be sent with the URL and results in a GET variable. What is wrong, respectively what must be done, that dataProvider will be sent as POST variable?
Part of my controller is:
public function actionAddproduct($order, $product){
// look for GET variable
$request = Yii::$app->request->get('data');
$dataProvider = $request['params']['dataProvider'];
// look for POST variable
$param1 = Yii::$app->request->post('dataProvider', null);
$dataProvider_suppliers_orders_products = $dataProvider;
return $this->actionView($order);
}
First of all you are passing the data-params in the url parameter rather than setting in the options parameter, so yes it will always be sent as query string no matter you pull your hairs off and become bald ¯\_(ツ)_/¯.
Then According to the DOCS
If the attribute is a data attribute as listed in
yii\helpers\Html::$dataAttributes, such as data or ng, a list of
attributes will be rendered, one for each element in the value array.
For example, 'data' => ['id' => 1, 'name' => 'yii'] generates
data-id="1" data-name="yii" and 'data' => ['params' => ['id' => 1,
'name' => 'yii'], 'status' => 'ok'] generates
data-params='{"id":1,"name":"yii"}' data-status="ok"
So, you need to change the anchor to look like
Html::a($data['name'], ['suppliers_orders/addproduct', 'order' => $model->id, 'product' => $data['id']], [
'data' => [
'method' => 'POST',
'params' => ['dataProvider' => $dataProvider_products]
]
]);
But since you are passing the $dataProvider object to the params it aint going to work because it will be changed to [Object Object] but if it is simple text then it will work, otherwise you have to change your approach.
Your complete code for the GridView should look like below
<?=
GridView::widget([
'dataProvider' => $dataProvider_products,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Name',
'format' => 'raw',
'value' => function ($data) use ($model, $dataProvider_products) {
return Html::a($data['name'], ['suppliers_orders/addproduct', 'order' => $model->id, 'product' => $data['id']], [
'data' => [
'method' => 'POST',
'params' => ['dataProvider' => $dataProvider_products]
]
]);
},
],
'supplier_product_number',
'size',
'price_net',
],
]);
?>
I have a huge array full of a bunch of hashes. What I need to do is single out one index hash from the array that meets a specific criteria. (doing this due to an rspec test, but having trouble singling out one of them)
My array is like this
[
{
"name" => "jon doe",
"team" => "team2",
"price" => 2000,
"eligibility_settings" => {}
},
{
"name" => "jonny doe",
"team" => "team1",
"value" => 2000,
"eligibility_settings" => {
"player_gender" => male,
"player_max_age" => 26,
"player_min_age" => 23,
"established_union_only" => true
}
},
{
"name" => "jonni doe",
"team" => "team3",
"price" => 2000,
"eligibility_settings" => {}
},
]
I need to single out the second one, based on its eligibility settings. I just took three of them from my array, have lots more, so simple active record methods like (hash.second) won't work in this instance.
I've tried things like
players.team.map(&:hash).find{ |x| x[ 'eligibility_settings?' ] == true}
However when I try this, I get a nil response. (which is odd)
I've also looked into using the ruby detect method, which hasn't gotten me anywhere either
Players.team.map(&:hash).['hash.seligibiltiy_settings'].detect { true }
Would anybody have any idea what to do with this one?
Notes
players.team.map(&:hash).find{ |x| x[ 'eligibility_settings?' ] == true}
Players.team.map(&:hash).['hash.seligibiltiy_settings'].detect { true }
Is is players or Players ?
Why is it plural?
If you can call map on team, it probably should be plural
Why do you convert to a hash?
eligibility_settings? isn't a key in your hash. eligibility_settings is
eligibility_settings can be a hash, but it cannot be true
If you want to check if it isn't empty, use !h['eligibility_settings'].empty?
Possible solution
You could use :
data = [
{
'name' => 'jon doe',
'team' => 'team2',
'price' => 2000,
'eligibility_settings' => {}
},
{
'name' => 'jonny doe',
'team' => 'team1',
'value' => 2000,
'eligibility_settings' => {
'player_gender' => 'male',
'player_max_age' => 26,
'player_min_age' => 23,
'established_union_only' => true
}
},
{
'name' => 'jonni doe',
'team' => 'team3',
'price' => 2000,
'eligibility_settings' => {}
}
]
p data.find { |h| !h['eligibility_settings'].empty? }
# {"name"=>"jonny doe", "team"=>"team1", "value"=>2000, "eligibility_settings"=>{"player_gender"=>"male", "player_max_age"=>26, "player_min_age"=>23, "established_union_only"=>true}}
If h['eligibility_settings'] can be nil, you can use :
data.find { |h| !h['eligibility_settings'].blank? }
or
data.find { |h| h['eligibility_settings'].present? }