#RestController - Collection issue - angularjs

I am implementing a spring boot application using #RestController w/ Angular.js client and I want to create/update a Group with one or multiple Users (as children). This does not work with multiple users.
Model Signature:
Grp {
externalId (string, optional),
grpOwner (User, optional),
grpTxt (string, optional),
users (Array[User], optional)
}
User {
externalId (string, optional),
username (string, optional)
}
grp.json (both users exist in database)
{
"externalId": "G0000001",
"users": [
{
"username": "admin"
},
{
"username": "system"
}
]
})
When trying to create/update one Group w/ multiple users, only the first one is taken into consideration. Actually, when debugging the Java part. Any idea?
#RequestMapping(method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<Grp> updateGrp(#RequestBody Grp grp) throws URISyntaxException {
log.debug("REST request to update Grp : {}", grp);
// Check if the group has been created
Optional<Grp> oGrp = gDao.findOneByExternalIdAndGrpOwner(grp.getExternalId(), this.getCurrentUser());
if (oGrp.isPresent()) {
Grp mGrp = oGrp.get();
this.merge(mGrp, grp);
Grp result = gDao.save(mGrp);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert("grp", grp.getExternalId().toString()))
.body(result);
}
return createGrp(grp);
}
Trace:
2016-07-06 11:29:12.563 DEBUG 3216 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing PUT request for [/api/grps]
2016-07-06 11:29:12.566 DEBUG 3216 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /api/grps
2016-07-06 11:29:12.567 DEBUG 3216 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<com.coopyrightcode.common.domain.Grp> com.coopyrightcode.common.web.rest.GrpResource.updateGrp(com.coopyrightcode.common.domain.Grp) throws java.net.URISyntaxException]
2016-07-06 11:29:12.604 DEBUG 3216 --- [nio-8080-exec-5] m.m.a.RequestResponseBodyMethodProcessor : Read [class com.coopyrightcode.common.domain.Grp] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#4982ce48]
2016-07-06 11:29:12.613 DEBUG 3216 --- [nio-8080-exec-5] c.c.common.aop.logging.LoggingAspect : Enter: com.coopyrightcode.common.web.rest.GrpResource.updateGrp() with argument[s] = [Grp [grpTxt=null, grpOwner=null, users=[User [username=admin, password=null, fName=null, lName=null, email=null, activated=false, langKey=null, appKey=63d71c52-95cd-43db-9, resetKey=3dfaf9f7-b46d-4daf-9, resetDate=null, usrAccountNonLocked=true, usrAccountNonExpired=true, usrCredentialsNonExpired=true, usrBio=null, usrMobile=null, usrPhone=null, usrPics=null, usrReferent=null, usrCtrId=null]]]]
2016-07-06 11:29:12.613 DEBUG 3216 --- [nio-8080-exec-5] c.c.common.web.rest.PortfolioResource : REST request to update Grp : Grp [grpTxt=null, grpOwner=null, users=[User [username=admin, password=null, fName=null, lName=null, email=null, activated=false, langKey=null, appKey=63d71c52-95cd-43db-9, resetKey=3dfaf9f7-b46d-4daf-9, resetDate=null, usrAccountNonLocked=true, usrAccountNonExpired=true, usrCredentialsNonExpired=true, usrBio=null, usrMobile=null, usrPhone=null, usrPics=null, usrReferent=null, usrCtrId=null]]]

Related

Springboot #DataJpaTest Integration test with external sql server db

I have below repository class in my spring boot project. This repository has a method that returns Inventory data from the SQL server. This is working on my project.
#Repository
public interface InventoryRepository extends JpaRepository<Inventory, Integer> {
Inventory findByInventoryIdAndCompanyId(Integer inventoryId, Integer companyId);
}
I want to write a integration for the repository which should get data from dev and test environment SQL server DB.
This dev and test environment db has data already.
Below are the application.yml files in my resources folder (I have changed url and credential intentionally to show here).
application.yml :
spring:
profiles.active: development
application-developement.yml :
spring:
profiles: development
spring.datasource.type: com.zaxxer.hikari.HikariDataSource
spring.datasource.jdbc-url: jdbc:sqlserver://22.22.22.22:1533;instanceName=SQLSVR;databaseName=dev
spring.datasource.username: admin
spring.datasource.password: admin
spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
application-test.yml :
spring:
profiles: test
spring.datasource.type: com.zaxxer.hikari.HikariDataSource
spring.datasource.jdbc-url: jdbc:sqlserver://11.11.11.11:1533;instanceName=SQLSVR;databaseName=qa
spring.datasource.url: jdbc:sqlserver://11.11.11.11:1533;instanceName=SQLSVR;databaseName=qa
spring.datasource.username: admin
spring.datasource.password: admin
spring.datasource.driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
Below is the test class for my repository.
#ExtendWith(SpringExtension.class)
#DataJpaTest
#ContextConfiguration
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class InventoryRepositoryTest {
#Autowired
InventoryRepository inventoryRepository;
#Test
public void getRepositoryByIdTest () {
Assertions.assertEquals(1,inventoryRepository.findByInventoryIdAndCompanyId(1,1));
}
}
Below is the error I am getting while performing this test
2021-10-18 03:35:38.917 INFO 11968 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext#18d87d80 testClass = InventoryRepositoryTest, testInstance = com.cropin.mwarehouse.common.repository.InventoryRepositoryTest#437da279, testMethod = getRepositoryByIdTest#InventoryRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#618425b5 testClass = InventoryRepositoryTest, locations = '{}', classes = '{class com.cropin.mwarehouse.CropinMWarehouseServiceApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer#58695725 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4b2bac3f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#26794848, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer#6ad82709, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer#351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#fb6c1252, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#158a8276], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager#f310675]; rollback [true]
2021-10-18 03:35:38.963 DEBUG 11968 --- [ main] org.hibernate.SQL :
select
inventory0_.inventoryId as inventor1_10_,
inventory0_.createdBy as createdB2_10_,
inventory0_.createdDate as createdD3_10_,
inventory0_.lastModifiedBy as lastModi4_10_,
inventory0_.lastModifiedDate as lastModi5_10_,
inventory0_.balanceWeight as balanceW6_10_,
inventory0_.batchCreationDate as batchCre7_10_,
inventory0_.batchNumber as batchNum8_10_,
inventory0_.clientId as clientId9_10_,
inventory0_.companyId as company10_10_,
inventory0_.currencyUnitId as currenc11_10_,
inventory0_.dateOfEntry as dateOfE12_10_,
inventory0_.harvestReferenceId as harvest13_10_,
inventory0_.inventoryStatus as invento14_10_,
inventory0_.isActive as isActiv15_10_,
inventory0_.itemId as itemId16_10_,
inventory0_.locationId as locatio17_10_,
inventory0_.parentInventoryId as parentI18_10_,
inventory0_.processId as process19_10_,
inventory0_.quantity as quantit20_10_,
inventory0_.quantityBalance as quantit21_10_,
inventory0_.supplierId as supplie22_10_,
inventory0_.unitPrice as unitPri23_10_,
inventory0_.weight as weight24_10_
from
inv.Inventory inventory0_
where
inventory0_.inventoryId=?
and inventory0_.companyId=?
Hibernate:
select
inventory0_.inventoryId as inventor1_10_,
inventory0_.createdBy as createdB2_10_,
inventory0_.createdDate as createdD3_10_,
inventory0_.lastModifiedBy as lastModi4_10_,
inventory0_.lastModifiedDate as lastModi5_10_,
inventory0_.balanceWeight as balanceW6_10_,
inventory0_.batchCreationDate as batchCre7_10_,
inventory0_.batchNumber as batchNum8_10_,
inventory0_.clientId as clientId9_10_,
inventory0_.companyId as company10_10_,
inventory0_.currencyUnitId as currenc11_10_,
inventory0_.dateOfEntry as dateOfE12_10_,
inventory0_.harvestReferenceId as harvest13_10_,
inventory0_.inventoryStatus as invento14_10_,
inventory0_.isActive as isActiv15_10_,
inventory0_.itemId as itemId16_10_,
inventory0_.locationId as locatio17_10_,
inventory0_.parentInventoryId as parentI18_10_,
inventory0_.processId as process19_10_,
inventory0_.quantity as quantit20_10_,
inventory0_.quantityBalance as quantit21_10_,
inventory0_.supplierId as supplie22_10_,
inventory0_.unitPrice as unitPri23_10_,
inventory0_.weight as weight24_10_
from
inv.Inventory inventory0_
where
inventory0_.inventoryId=?
and inventory0_.companyId=?
2021-10-18 03:35:39.142 DEBUG 11968 --- [ main] org.hibernate.SQL :
select
companymas0_.companyId as companyI1_1_0_,
companymas0_.createdBy as createdB2_1_0_,
companymas0_.createdDate as createdD3_1_0_,
companymas0_.lastModifiedBy as lastModi4_1_0_,
companymas0_.lastModifiedDate as lastModi5_1_0_,
companymas0_.companyAddress as companyA6_1_0_,
companymas0_.companyCode as companyC7_1_0_,
companymas0_.companyDesc as companyD8_1_0_,
companymas0_.companyLogo as companyL9_1_0_,
companymas0_.companyName as company10_1_0_,
companymas0_.companyPreferredSubDomain as company11_1_0_,
companymas0_.contactEmail as contact12_1_0_,
companymas0_.contactNumber as contact13_1_0_,
companymas0_.defaultRadiusForGeoFencing as default14_1_0_,
companymas0_.fiscalMonth as fiscalM15_1_0_,
companymas0_.isGDPRRequired as isGDPRR16_1_0_,
companymas0_.isActive as isActiv17_1_0_,
companymas0_.isBlueToothRequired as isBlueT18_1_0_,
companymas0_.isGeoFencingRequired as isGeoFe19_1_0_,
companymas0_.isHarvestPaid as isHarve20_1_0_,
companymas0_.isShareImage as isShare21_1_0_,
companymas0_.isVerified as isVerif22_1_0_,
companymas0_.isZohoEnable as isZohoE23_1_0_,
companymas0_.planTypeId as planTyp24_1_0_,
companymas0_.primaryCountry as primary25_1_0_,
companymas0_.sTA as sTA26_1_0_,
companymas0_.webSite as webSite27_1_0_
from
dbo.CompanyMaster companymas0_
where
companymas0_.companyId=?
Hibernate:
select
companymas0_.companyId as companyI1_1_0_,
companymas0_.createdBy as createdB2_1_0_,
companymas0_.createdDate as createdD3_1_0_,
companymas0_.lastModifiedBy as lastModi4_1_0_,
companymas0_.lastModifiedDate as lastModi5_1_0_,
companymas0_.companyAddress as companyA6_1_0_,
companymas0_.companyCode as companyC7_1_0_,
companymas0_.companyDesc as companyD8_1_0_,
companymas0_.companyLogo as companyL9_1_0_,
companymas0_.companyName as company10_1_0_,
companymas0_.companyPreferredSubDomain as company11_1_0_,
companymas0_.contactEmail as contact12_1_0_,
companymas0_.contactNumber as contact13_1_0_,
companymas0_.defaultRadiusForGeoFencing as default14_1_0_,
companymas0_.fiscalMonth as fiscalM15_1_0_,
companymas0_.isGDPRRequired as isGDPRR16_1_0_,
companymas0_.isActive as isActiv17_1_0_,
companymas0_.isBlueToothRequired as isBlueT18_1_0_,
companymas0_.isGeoFencingRequired as isGeoFe19_1_0_,
companymas0_.isHarvestPaid as isHarve20_1_0_,
companymas0_.isShareImage as isShare21_1_0_,
companymas0_.isVerified as isVerif22_1_0_,
companymas0_.isZohoEnable as isZohoE23_1_0_,
companymas0_.planTypeId as planTyp24_1_0_,
companymas0_.primaryCountry as primary25_1_0_,
companymas0_.sTA as sTA26_1_0_,
companymas0_.webSite as webSite27_1_0_
from
dbo.CompanyMaster companymas0_
where
companymas0_.companyId=?
2021-10-18 03:35:39.292 DEBUG 11968 --- [ main] org.hibernate.SQL :
select
locationma0_.locationId as location1_22_0_,
locationma0_.createdBy as createdB2_22_0_,
locationma0_.createdDate as createdD3_22_0_,
locationma0_.lastModifiedBy as lastModi4_22_0_,
locationma0_.lastModifiedDate as lastModi5_22_0_,
locationma0_.addressLine1 as addressL6_22_0_,
locationma0_.addressLine2 as addressL7_22_0_,
locationma0_.companyId as companyI8_22_0_,
locationma0_.coordinates as coordina9_22_0_,
locationma0_.districtId as distric10_22_0_,
locationma0_.geoId as geoId11_22_0_,
locationma0_.imageName as imageNa12_22_0_,
locationma0_.isActive as isActiv13_22_0_,
locationma0_.latitude as latitud14_22_0_,
locationma0_.locationTypeId as locatio15_22_0_,
locationma0_.longitude as longitu16_22_0_,
locationma0_.name as name17_22_0_,
locationma0_.parentLocationId as parentL18_22_0_,
locationma0_.pincode as pincode19_22_0_,
locationma0_.placeName as placeNa20_22_0_,
locationma0_.stateId as stateId21_22_0_
from
inv.LocationMaster locationma0_
where
locationma0_.locationId=?
Hibernate:
select
locationma0_.locationId as location1_22_0_,
locationma0_.createdBy as createdB2_22_0_,
locationma0_.createdDate as createdD3_22_0_,
locationma0_.lastModifiedBy as lastModi4_22_0_,
locationma0_.lastModifiedDate as lastModi5_22_0_,
locationma0_.addressLine1 as addressL6_22_0_,
locationma0_.addressLine2 as addressL7_22_0_,
locationma0_.companyId as companyI8_22_0_,
locationma0_.coordinates as coordina9_22_0_,
locationma0_.districtId as distric10_22_0_,
locationma0_.geoId as geoId11_22_0_,
locationma0_.imageName as imageNa12_22_0_,
locationma0_.isActive as isActiv13_22_0_,
locationma0_.latitude as latitud14_22_0_,
locationma0_.locationTypeId as locatio15_22_0_,
locationma0_.longitude as longitu16_22_0_,
locationma0_.name as name17_22_0_,
locationma0_.parentLocationId as parentL18_22_0_,
locationma0_.pincode as pincode19_22_0_,
locationma0_.placeName as placeNa20_22_0_,
locationma0_.stateId as stateId21_22_0_
from
inv.LocationMaster locationma0_
where
locationma0_.locationId=?
2021-10-18 03:35:39.663 INFO 11968 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext#18d87d80 testClass = InventoryRepositoryTest, testInstance = com.cropin.mwarehouse.common.repository.InventoryRepositoryTest#437da279, testMethod = getRepositoryByIdTest#InventoryRepositoryTest, testException = org.opentest4j.AssertionFailedError: expected: <1> but was: <com.cropin.mwarehouse.common.entity.Inventory#5b58f639>, mergedContextConfiguration = [MergedContextConfiguration#618425b5 testClass = InventoryRepositoryTest, locations = '{}', classes = '{class com.cropin.mwarehouse.CropinMWarehouseServiceApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer#58695725 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#4b2bac3f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#26794848, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer#6ad82709, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer#351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#fb6c1252, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#158a8276], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]
org.opentest4j.AssertionFailedError:
Expected :1
Actual :com.cropin.mwarehouse.common.entity.Inventory#5b58f639
<Click to see difference>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
at com.cropin.mwarehouse.common.repository.InventoryRepositoryTest.getRepositoryByIdTest(InventoryRepositoryTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Below are the questions for which I am looking for an answers:
Does #DataJpaTest only works with in memory db? Here I am trying to connect with external sql server db is it really connecting to it?
If #DataJpaTest is able to connect to external sql server db then why it is failing as I already have records available for above test parameter.
3.How Can I use profiling here? There is an option as #ActiveProfile but I want to use same block of test for both the environment dev and qa, in that how this profiling will work?
4.In error log it is showing active profile as empty, what does that mean? Is it not picking up the development profile?
How can I achieve integration test connecting to my dev and qa db which already has data. I don't want to use in memory db.
Please help me out with this question.
The actual connection seems to work. #DataJpaTest works with any DataSource configuration, it just takes the opinionated approach to use an in-memory database. You already added the required code to opt-out and use your own DataSource with:
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
The actual test failure happens because you try to compare an int with an actual Java object. Either return all objects and check the size:
Assertions.assertEquals(1, inventoryRepository.findAll().size());
... or assert that the result is not null:
Assertions.assertNotNull(inventoryRepository.findByInventoryIdAndCompanyId(1,1));
Take a closer look at the assertion error:
org.opentest4j.AssertionFailedError:
Expected :1
Actual :com.cropin.mwarehouse.common.entity.Inventory#5b58f639
<Click to see difference>
FYI: You should be able to reduce the test setup to:
// #ExtendWith(SpringExtension.class) already comes with #DataJpaTest
#DataJpaTest
// #ContextConfiguration
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class InventoryRepositoryTest {

Camel-SCR ( Declarative Services ) not able to access javax.sql.DataSource

I have created datssource service with pax-jdbc-config and following URL
https://ops4j1.jira.com/wiki/spaces/PAXJDBC/pages/61767710/Create+DataSource+from+config
Now datasource service is available
karaf#root()> service:list javax.sql.DataSource
[javax.sql.DataSource]
----------------------
dataSourceName = MySqlDS
felix.fileinstall.filename = file:/C:/Apache/apache-karaf-4.2.0/etc/org.ops4j.datasource-MySqlDS.cfg
osgi.jdbc.driver.class = com.mysql.jdbc.Driver
osgi.jdbc.driver.name = mysql
osgi.jndi.service.name = java:/MySqlDS
password = root
service.bundleid = 102
service.factoryPid = org.ops4j.datasource
service.id = 147
service.pid = org.ops4j.datasource.eaeb33be-1dcc-4f56-b9f3-37f5185ad761
service.scope = singleton
url = jdbc:mysql://localhost:3306/test
user = root
Provided by :
OPS4J Pax JDBC Config (102)
But while running my camel-scr route i am getting below error
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: MySqlDS of type: javax.sql.DataSource
at org.apache.camel.util.CamelContextHelper.mandatoryLookupAndConvert(CamelContextHelper.java:201) ~[76:org.apache.camel.camel-core:2.19.5]
at org.apache.camel.util.EndpointHelper.resolveReferenceParameter(EndpointHelper.java:326) ~[76:org.apache.camel.camel-core:2.19.5]
at org.apache.camel.util.EndpointHelper.resolveReferenceParameter(EndpointHelper.java:308) ~[76:org.apache.camel.camel-core:2.19.5]
at org.apache.camel.impl.DefaultComponent.resolveAndRemoveReferenceParameter(DefaultComponent.java:415) ~[76:org.apache.camel.camel-core:2.19.5]
at org.apache.camel.impl.DefaultComponent.resolveAndRemoveReferenceParameter(DefaultComponent.java:394) ~[76:org.apache.camel.camel-core:2.19.5]
at org.apache.camel.component.sql.SqlComponent.createEndpoint(SqlComponent.java:62) ~[131:org.apache.camel.camel-sql:2.19.5]
at org.apache.camel.impl.DefaultComponent.createEndpoint(DefaultComponent.java:116) ~[76:org.apache.camel.camel-core:2.19.5]
at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:676) ~[76:org.apache.camel.camel-core:2.19.5]
at org.apache.camel.util.CamelContextHelper.getMandatoryEndpoint(CamelContextHelper.java:80) ~[76:org.apache.camel.camel-core:2.19.5]
Camel SCR Runner snippet:
protected void setupCamelContext(BundleContext bundleContext, String camelContextId)throws Exception{
super.setupCamelContext(bundleContext, camelContextId);
getContext().setUseMDCLogging(true);
getContext().setUseBreadcrumb(true);
SqlComponent sql = new SqlComponent();
getContext().addComponent("sql", sql);
}
Camel Route
public void configure() throws Exception {
// Add a bean to Camel context registry
AbstractCamelRunner.getRegistry(getContext(), SimpleRegistry.class).put("testString", "this is a test");
from("{{from}}")
.to("sql:select * from table?dataSource=#MySqlDS&outputType=StreamList&outputClass=org.apache.camel.component.sql.ProjectModel")
.to("log:stream")
.split(body()).streaming()
.to("log:row")
.to("mock:result")
.end();
}
As i am using #MySqlDS which suppose to take it from service registry or i have to add in setupcamelcontext and how??
Camel SQL Component expects a reference when you use the dataSource= option.
MySqlDS is the osgi.jndi.service.name and not the reference id

transaction isolation level (READ UNCOMMITTED) of Spring Batch

I want to set transaction isolation level to READ UNCOMMITTED, but is doesn't work.
Here is my job source.
TestJobConfiguration.java
#Slf4j
#Configuration
public class TestJobConfiguration {
#Autowired
private JobBuilderFactory jobBuilders;
#Autowired
private CustomJobExecutionListener customJobExecutionListener;
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
private StepBuilderFactory stepBuilders;
#Bean(name = "testJob")
public Job job() {
JobBuilder jobBuilder = jobBuilders.get("testJob").listener(customJobExecutionListener);
Step step = stepBuilders.get("testStep").tasklet(count()).transactionAttribute(transactionAttr())
.build();
return jobBuilder.start(step).build();
}
public TransactionAttribute transactionAttr() {
RuleBasedTransactionAttribute tr = new RuleBasedTransactionAttribute();
tr.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
return tr;
}
public Tasklet count() {
return new Tasklet() {
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext context) {
StringBuilder countSql = new StringBuilder();
countSql.append(" SELECT COUNT(id)");
countSql.append(" FROM user");
log.debug("test start");
int count = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
contribution.incrementWriteCount(count);
log.debug("test end");
log.debug("count : {}", count);
return RepeatStatus.FINISHED;
}
};
}
}
I executed below sql statement in Microsoft SQL Server Management Studio, and executed TestJob.
begin tran
delete from user
I expected to complete job, but it stopped at sql execution point.
My log is below.
...
2017-08-29T12:21:23.555+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test start
When I change my sql statement, countSql.append(" SELECT COUNT(id)"); to countSql.append(" SELECT COUNT(id) WITH (READUNCOMMITTED)"); it works.
...
2017-08-29T13:44:43.692+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test start
2017-08-29T13:44:43.726+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : test end
2017-08-29T13:44:43.726+09:00 DEBUG --- [ main] c.p.l.b.rank.job.TestJobConfiguration : count : 15178
2017-08-29T13:44:43.747+09:00 INFO --- [ main] c.p.l.b.l.CustomJobExecutionListener :
<!-----------------------------------------------------------------
Protocol for testJob
Started : Tue Aug 29 13:44:43 KST 2017
Finished : Tue Aug 29 13:44:43 KST 2017
Exit-Code : COMPLETED
Exit-Descr. :
Status : COMPLETED
Job-Parameter:
date=2017-08-29 13:44:43 +0900
JOB process time : 0sec
----------------------------------------------------------------->
Why doesn't work isolation level of transaction attribute??

How to use RESTfulWebServiceClient for php server in CN1

I want to generate the code for the server in php and use it as the backend instead of webservices in java. I noticed that, webservices Wizard in CN1 generated details on the server side. In my own case I want to create the server in php and use RESTfulWebServiceClient to point to the url.
Pls how do I go about this?
Is there any webservice Wizard that can generate the php server like java in netbeans?
In the auto re-new subscription in in-app purchase can I interact with the mysql database without using RESTfulWebServiceClient?
Thanks for your response
I have created the webservices in php and used the url in codename one. I was able to use the url to submit receipt into the database. see the image below
I still have challenges, the error code below was generated
[EDT] 0:0:0,0 - Codename One revisions: 3dc2fe6c4df57ff264ea094d13e0275639b780862293
[EDT] 0:0:0,0 - Receipts were last refreshed at Fri Mar 17 07:30:21 WAT 2017 so we won't refetch.
WARNING: Apple will no longer accept http URL connections from applications you tried to connect to http://slimapp/api/customer/add to learn more check out https://www.codenameone.com/blog/ios-http-urls.html
[Task Thread] 0:0:0,417 - Expected null for key value while parsing JSON token at row: 1 column: 44 buffer:
[Task Thread] 0:0:0,417 - Expected true for key value while parsing JSON token at row: 1 column: 47 buffer:
[Task Thread] 0:0:0,417 - Expected null for key value while parsing JSON token at row: 1 column: 49 buffer:
[Task Thread] 0:0:0,417 - Expected null for key value while parsing JSON token at row: 1 column: 52 buffer:
[Task Thread] 0:0:0,417 - Expected true for key value while parsing JSON token at row: 1 column: 57 buffer: l
[Task Thread] 0:0:0,417 - Expected null for key value while parsing JSON token at row: 1 column: 70 buffer: 1048l
[Task Thread] 0:0:0,417 - Expected null for key value while parsing JSON token at row: 1 column: 88 buffer: 1048l
java.lang.NumberFormatException: For input string: "1048le"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.codename1.io.JSONParser.parse(JSONParser.java:286)
at com.codename1.io.JSONParser.parseJSON(JSONParser.java:427)
at com.codename1.ws.RESTfulWebServiceClient.lambda$null$6(RESTfulWebServiceClient.java:204)
at com.codename1.ui.Display$1.run(Display.java:806)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
WARNING: Apple will no longer accept http URL connections from applications you tried to connect to http://slimapp/api/customer/add to learn more check out https://www.codenameone.com/blog/ios-http-urls.html
[Task Thread] 0:0:8,888 - Expected null for key value while parsing JSON token at row: 1 column: 44 buffer:
[Task Thread] 0:0:8,888 - Expected true for key value while parsing JSON token at row: 1 column: 47 buffer:
[Task Thread] 0:0:8,888 - Expected null for key value while parsing JSON token at row: 1 column: 49 buffer:
[Task Thread] 0:0:8,888 - Expected null for key value while parsing JSON token at row: 1 column: 52 buffer:
[Task Thread] 0:0:8,888 - Expected true for key value while parsing JSON token at row: 1 column: 57 buffer: l
[Task Thread] 0:0:8,888 - Expected null for key value while parsing JSON token at row: 1 column: 70 buffer: 1048l
[Task Thread] 0:0:8,888 - Expected null for key value while parsing JSON token at row: 1 column: 88 buffer: 1048l
java.lang.NumberFormatException: For input string: "1048le"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.codename1.io.JSONParser.parse(JSONParser.java:286)
at com.codename1.io.JSONParser.parseJSON(JSONParser.java:427)
at com.codename1.ws.RESTfulWebServiceClient.lambda$null$6(RESTfulWebServiceClient.java:204)
at com.codename1.ui.Display$1.run(Display.java:806)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
After subscribing and I press Syns Receipts. Subscribe to remove ads is still there. Pls help Thanks
This is my php webserver code.
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
$app->get('/api/customers', function (Request $request, Response $response) {
echo "customers";
// Get All customers
$sql = "SELECT * FROM receipts";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$customers = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($customers);
}catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
$app->get('/api/customers/{transactionId}', function (Request $request, Response $response) {
echo "customers";
$id = $request ->getAttribute("transactionId");
// Get single customers
$sql = "SELECT * FROM receipts where transaction_id = $id";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$customers = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($customers);
}catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
//add a user
$app->post('/api/customer/add', function (Request $request, Response $response) {
//echo "customers";
$transactionId = $request->getParam('transactionId');
$sku = $request->getParam('sku');
$purchaseDate = $request->getParam('purchaseDate');
$orderData = $request->getParam('orderData');
$storeCode = $request->getParam('storeCode');
echo "emmy ";
// (:transactionId,:sku,:purchaseDate,:orderData,:storeCode)";
// 'transactionid'
$sql = "INSERT INTO receipts(transaction_id,sku,purchase_date,order_data,store_code)VALUES
(:transactionid,:sku,:purchaseDate,:orderData,:storeCode)";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':transactionid', $transactionId);
$stmt->bindParam(':sku', $sku);
$stmt->bindParam(':purchaseDate', $purchaseDate);
$stmt->bindParam(':orderData', $orderData);
$stmt->bindParam(':storeCode', $storeCode);
$stmt->execute();
echo '{"notice": {"text": "customar added"}';
}catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
This is my url and part of my code in codename name:
private static final String receiptsEndpoint = "http://slimapp/api/customers";
private static final String receiptsEndpoint2 = "http://slimapp/api/customer/add";
private ReceiptStore createReceiptStore() {
return new ReceiptStore() {
RESTfulWebServiceClient client = createRESTClient(receiptsEndpoint);
RESTfulWebServiceClient client2 = createRESTClient(receiptsEndpoint2);
#Override
public void fetchReceipts(SuccessCallback<Receipt[]> callback) {
RESTfulWebServiceClient.Query query = new RESTfulWebServiceClient.Query() {
#Override
protected void setupConnectionRequest(RESTfulWebServiceClient client, ConnectionRequest req) {
super.setupConnectionRequest(client, req);
// req.setPost(true);
// req.setHttpMethod("post"); //Change to GET if necessary
req.setUrl(receiptsEndpoint);
}
protected void setupConnectionRequest2(RESTfulWebServiceClient client2, ConnectionRequest req2) {
super.setupConnectionRequest(client, req2);
req2.setPost(true);
req2.setHttpMethod("post"); //Change to GET if necessary
req2.setUrl(receiptsEndpoint2);
}
};
client.find(query, rowset->{
List<Receipt> out = new ArrayList<Receipt>();
for (Map m : rowset) {
Result res = Result.fromContent(m);
Receipt r = new Receipt();
r.setTransactionId(res.getAsString("transactionId"));
System.out.println(r.getTransactionId()+" ko");
r.setPurchaseDate(new Date(res.getAsLong("purchaseDate")));
r.setQuantity(1);
r.setSku(res.getAsString("sku"));
if (m.containsKey("cancellationDate") && m.get("cancellationDate") != null) {
r.setCancellationDate(new Date(res.getAsLong("cancellationDate")));
}
if (m.containsKey("expiryDate") && m.get("expiryDate") != null) {
r.setExpiryDate(new Date(res.getAsLong("expiryDate")));
}
out.add(r);
}
callback.onSucess(out.toArray(new Receipt[out.size()]));
});
}
#Override
public void submitReceipt(Receipt r, SuccessCallback<Boolean> callback) {
Map m = new HashMap();
m.put("transactionId", r.getTransactionId());
m.put("sku", r.getSku());
m.put("purchaseDate", r.getPurchaseDate().getTime());
m.put("orderData", r.getOrderData());
m.put("storeCode", r.getStoreCode());
System.out.println(r.getTransactionId());
client2.create(m, callback);
}
};
}
pls help to review my code in above what I am missing maybe in php webserver code or in codename one code. I was able to subscribe and receive the message that the subscription was succesfull and the records was inserted into the database, when I click on Syns Receipts Button, No receipt was updated and the record goes to the database. Pls help, I dont know what is going wrong
Our webservice wizard expects a Java server and doesn't generate PHP code.
You can use any restful service from Codename One by using ConnectionRequest and invoking a URL with GET, POST, PUT & DELETE.
See the developer guide section on networking. If you create a webservice in PHP and have the curl usage I can help with the Codename One equivalent.

Rails 4 Nested Attributes with fields_for Don't Save to Database

I want to create records on two different tables (venue and parking) via one form using accepts_nested_attributes_for. I want a user to be able to create a new venue, and also specify the parking options available to that venue via checkboxes. When I submit the form, the record for the containing model (venue) is created, but nothing happens with the nested model (parking). When I check the response from the server, I see that I'm encountering "Unpermitted parameters: parking_attributes," although I'm not sure why.
I've watched Railscast #196 Nested Model Form, and tried the suggestions from multiple stackoverflow posts (Rails 4 nested attributes not saving, Rails 4: fields_for in fields_for, and Rails 4 - Nested models(2 levels) not saving). If anybody can help me out, I'd greatly appreciate it.
I've included the two models, the venues controller, the venues/new view, and the response from the server.
venue.rb
class Venue < ActiveRecord::Base
has_many :parkings
accepts_nested_attributes_for :parkings
end
parking.rb
class Parking < ActiveRecord::Base
belongs_to :venue
end
venues_controller.rb
class VenuesController < ApplicationController
def index
#venues = Venue.all
end
def new
#venue = Venue.new
end
def create
#venue = Venue.new(venue_params)
if #venue.save
redirect_to #venue, flash: { success: "Venue successfully created" }
else
render :new
end
end
def show
#venue = Venue.find(params[:id])
end
def edit
#venue = Venue.find(params[:id])
end
def update
#venue = Venue.find(params[:id])
if #venue.update(venue_params)
redirect_to #venue
else
render "edit"
end
end
def destroy
#venue = Venue.find(params[:id])
if #venue.destroy
redirect_to venues_path, flash: { success: "Venue successfully destroyed" }
else
render "show", flash: { error: "Venue was not successfully destroyed" }
end
end
private
def venue_params
params.require(:venue).permit(
:name,:address,:city,:state,:zip,
parking_attributes: [:id, :venue_id, :none, :street_free])
end
end
/venues/new.haml
%h1 Add a new venue
= form_for #venue do |f|
= f.label :name
= f.text_field :name
= f.label :address
= f.text_field :address
= f.label :city
= f.text_field :city
= f.label :state
= f.text_field :state
= f.label :zip
= f.text_field :zip
= f.fields_for :parkings do |p|
= p.label :none
= p.check_box :none
= p.label :street_free
= p.check_box :street_free
= f.submit
Server response
Started POST "/venues" for 127.0.0.1 at 2014-04-29 14:02:54 -0500
Processing by VenuesController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"kMcVVwXq7f22rIGm1rQ6+QzC80ScmXrVA2IE8TGbN7w=",
"venue"=>{"name"=>"The Five O'Clock Lounge",
"address"=>"11904 Detroit Ave",
"city"=>"Lakewood",
"state"=>"OH",
"zip"=>"44107",
"parkings_attributes"=>
{"0"=>
{"none"=>"1",
"street_free"=>"0"
}
}
},
"commit"=>"Create Venue"}
Unpermitted parameters: parkings_attributes
(0.2ms) BEGIN
SQL (107.0ms) INSERT INTO "venues" (
"address",
"city",
"created_at",
"name", "state",
"updated_at", "zip"
) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"
[
["address", "11904 Detroit Ave"],
["city", "Lakewood"],
["created_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["name", "The Five O'Clock Lounge"],
["state", "OH"],
["updated_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["zip", 44107]
]
SQL (47.5ms) INSERT INTO "parkings" (
"created_at",
"updated_at",
"venue_id") VALUES ($1, $2, $3) RETURNING "id"
[
["created_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["updated_at", Tue, 29 Apr 2014 19:02:54 UTC +00:00],
["venue_id", 10]
]
(0.6ms) COMMIT
Redirected to http://localhost:3000/venues/10
Completed 302 Found in 165ms (ActiveRecord: 155.2ms)
UPDATE: SOLVED
Following the advice of Kirti, I was able to get past the unpermitted parameters error.
Update venue_params method as below:
def venue_params
params.require(:venue).permit(
:name,:address,:city,:state,:zip,
parkings_attributes: [:id, :venue_id, :none, :street_free])
end
Notice parkings_attributes(plural parkings) and not parking_attributes(singular parking).
As you have 1-M relationship between Venue and Parking model you would receive parkings_attributes(plural parkings) in params hash BUT in your current code for venue_params you whitelisted parking_attributes(singular parking). This is causing the warning Unpermitted parameters: parkings_attributes

Resources