小编Chr*_*her的帖子

销毁空白嵌套属性

如果它的属性在父模型的表单中被消隐,我想销毁嵌套模型 - 但是,ActiveRecord::Callbacks如果模型为空,则看起来不会调用它.

class Artist < ActiveRecord::Base
  using_access_control
  attr_accessible :bio, :name, :tour_dates_attributes
  has_many :tour_dates, :dependent => :destroy
  accepts_nested_attributes_for :tour_dates, :reject_if => lambda { |a| a[:when].blank? || a[:where].blank? }, :allow_destroy => true
  validates :bio, :name :presence => true

  def to_param
    name
  end
end
Run Code Online (Sandbox Code Playgroud)

class TourDate < ActiveRecord::Base
  validates :address, :when, :where, :artist_id, :presence => true
  attr_accessible :address, :artist_id, :when, :where
  belongs_to :artist
  before_save :destroy_if_blank

  private
  def destroy_if_blank
    logger.info "destroy_if_blank called"
  end
end
Run Code Online (Sandbox Code Playgroud)

我有一个艺术家的表格,用于fields_for显示艺术家相关旅行日期的字段,用于编辑和添加新的旅行日期,但如果我只是删除一个旅游日期(删除它),destroy_if_blank则永远不会被调用.据推测,Artist控制器的@artist.update_attributes(params[:artist]) …

activerecord ruby-on-rails

31
推荐指数
4
解决办法
2万
查看次数

在github中避免使用ASP.NET密码?

我理解这个问题可以是一般的,但是,特别是关于ASP.NET MVC,什么是在本地保存密码但不在git/svn中的最佳方法?我的数据库连接字符串当前在web.config中 - 最好以某种方式在web.config中包含一个不在git中的文件?你们有什么人做的?

svn git passwords asp.net-mvc

7
推荐指数
2
解决办法
1872
查看次数

在上传.zip文件时,Rails的Paperclip gem而不是PUTting

我有一个表格(Rails 3.2.8,Paperclip 3.1.4),带有两个Paperclip附件,用于带有两个has_attached_files的模型.一个是图像,另一个是通用文件,通常是.zip文件.

只要我不尝试上传.zip文件,一切正常.上传任何大小的.zip文件(原始版本为80 MB但尝试3 MB以查看是否出现大小问题)会导致表单POST而不是PUT,并且Rails会引发路由错误.

表单方法是POST但是将Rails的隐藏_method值设置为'put',这样可以正常工作,并且在我不尝试上传.zip文件时会导致PUT.

该表单确实正确设置了enctype'multipart'位.

知道是什么原因引起的吗?

zip ruby-on-rails paperclip

7
推荐指数
1
解决办法
591
查看次数

In CorrectResultSizeDataAccessException - 尝试简单地获取最新行

我有一个名为“ImportReceiptRepository”的 Spring CrudRepository。

我只是想编写一个方法来获取 order by 子句中的第一行。

这是我目前正在使用的:

ImportReceipt importReceipt = this.importReceiptRepository.getOneByImportTypeOrderByTimestampDesc(importType);
Run Code Online (Sandbox Code Playgroud)

问题是,当返回多于一行时,Spring 会抛出:

org.springframework.dao.IncorrectResultSizeDataAccessException: result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements
Run Code Online (Sandbox Code Playgroud)

当返回 0-n 行时,我应该如何重命名这个 CrudRepository 函数以简单地获取第一行?

java sql spring spring-data

6
推荐指数
1
解决办法
3万
查看次数

过滤Rails'to_xml中的深层关联

我有一个具有多个角色的Person对象.反过来,角色属于应用程序.我正在使用以下代码将这种深层关系呈现为XML:

format.xml { render :text => @person.to_xml( :include => { :roles => { :include => :application } } ) }
Run Code Online (Sandbox Code Playgroud)

渲染出这样的东西:

<person>
  <email>****@****.edu</email>
  <first>Christopher</first>
  <last>****</last>
  <loginid>****</loginid>
  <roles type="array">
    <role>
      <application-id type="integer">3</application-id>
      <name>Access</name>
      <application>
        <name>****</name>
      </application>
    </role>
    <role>
      <application-id type="integer">2</application-id>
      <name>Create Ballots</name>
      <application>
        <name>****</name>
      </application>
    </role>
  </roles>
</person>
Run Code Online (Sandbox Code Playgroud)

但是,这有效,我想过滤它显示的应用程序和角色.我只想显示application_id是某个整数的角色(因此,嵌套在它们中,应用程序).例如,如果我只查找application_id == 3,则输出以下内容:

<person>
  <email>****@****.edu</email>
  <first>Christopher</first>
  <last>****</last>
  <loginid>****</loginid>
  <roles type="array">
    <role>
      <application-id type="integer">3</application-id>
      <name>Access</name>
      <application>
        <name>****</name>
      </application>
    </role>
  </roles>
</person>
Run Code Online (Sandbox Code Playgroud)

提前感谢您提供的任何帮助.

xml activerecord ruby-on-rails associations filter

5
推荐指数
1
解决办法
293
查看次数

改变现有粒子的方向

我正在使用SpriteKit的粒子发射器系统在背景中构建一个移动的星形场,其中玩家的船位于屏幕的中心.

当玩家触摸屏幕的某个区域时,我会计算角度并为玩家精灵转动该方向设置动画.

但是,当我将它应用于星形场时,星形场的整个矩形都会旋转.然而,我想要的是,单个粒子只是开始向新方向移动.

这是将整张纸与整个点旋转并且仅使点移动到新角度之间的区别.那有意义吗?

这就是我到目前为止玩家正确旋转但星球场"像一整张纸一样旋转"的情况:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // Choose one of the touches to work with
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    CGPoint center = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));

    CGPoint offset = rwSub(location, center);

    SKEmitterNode *starfield = (SKEmitterNode *)[self childNodeWithName:@"starfield"];

    SKSpriteNode *player = (SKSpriteNode *)[self childNodeWithName:@"player"];

    SKAction *rotateNode = [SKAction rotateToAngle: (CGFloat)atan2(offset.y, offset.x) duration:0.5  shortestUnitArc:TRUE];
    [player runAction: rotateNode];

    SKAction *rotateStarfieldNode = [SKAction rotateToAngle: (CGFloat)(atan2(offset.y, offset.x) - M_PI_2) duration:0.5  shortestUnitArc:TRUE];
    [starfield runAction: rotateStarfieldNode];
}
Run Code Online (Sandbox Code Playgroud)

iphone particles ios sprite-kit skemitternode

5
推荐指数
1
解决办法
1293
查看次数

CrudRepository:由多个相关实体查找

我在CrudRepository中设计查询时遇到了一些麻烦.

我有两个实体,CourseOffering和Department(仅显示相关代码):

CourseOffering.java:

public class CourseOffering implements Serializable
{
    private Department department;

    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "DepartmentId", nullable = true)
    @JsonProperty
    public Department getDepartment()
    {
        return this.department;
    }

    public void setDepartment(Department department)
    {
        this.department = department;
    }
}
Run Code Online (Sandbox Code Playgroud)

Department.java:

public class Department implements Serializable
{
    private Set<CourseOffering> courses;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "department")
    public Set<CourseOffering> getCourses() {
        return this.courses;
    }

    public void setCourses(Set<CourseOffering> courses) {
        this.courses = courses;
    }
}
Run Code Online (Sandbox Code Playgroud)

和有问题的CrudRepository:

CourseOfferingRepository.java:

import java.util.List;
import …
Run Code Online (Sandbox Code Playgroud)

java sql spring hibernate spring-data

5
推荐指数
1
解决办法
1万
查看次数

Swift中免费的C-malloc()内存?

我正在使用Swift编译器的Bridging Header功能来调用使用分配内存的C函数malloc().然后它返回一个指向该内存的指针.函数原型是这样的:

char *the_function(const char *);
Run Code Online (Sandbox Code Playgroud)

在Swift中,我使用它像这样:

var ret = the_function(("something" as NSString).UTF8String)

let val = String.fromCString(ret)!
Run Code Online (Sandbox Code Playgroud)

请原谅我对Swift的无知,但通常在C中,如果the_function()是malloc的内存并返回它,那么其他人需要在某个时候释放()它.

这是由Swift以某种方式处理还是我在这个例子中泄漏内存?

提前致谢.

c pointers memory-management swift

5
推荐指数
1
解决办法
1798
查看次数

Spring transactions in scheduled task - detached entity error

(I know similar problems are all over SO but I cannot find a proper solution.)

I have a Spring scheduled task which reads and writes from the database via Spring Repositories/Hibernate, including a many-to-many relationship between two entities, requiring proper session management for the lazily initialized collection.

However, Spring appears not to properly manage the transaction despite the annotation.

What am I doing wrong?

(I should mention throwing a @Transactional on the same method that as a @Scheduled does work …

java spring hibernate transactions scheduled-tasks

4
推荐指数
1
解决办法
6041
查看次数

CrudRepository:返回一个按列排序的结果

有没有办法让CrudRepository接口对具有多行的表进行排序并简单地返回第一行,例如按时间戳排序以仅返回最新的行?

public interface ImportReceiptRepository extends CrudRepository<ImportReceipt, Long>
{
    ImportReceipt getOneByImportTypeOrderByTimestampDesc(String importType);
    ImportReceipt findOneByImportTypeOrderByTimestampDesc(String importType);
}
Run Code Online (Sandbox Code Playgroud)

findOneBy ...和getOneBy ... throw:

org.springframework.dao.IncorrectResultSizeDataAccessException: result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:395)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:216)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy109.findOneByImportTypeOrderByTimestampDesc(Unknown Source)
at edu.ucdavis.dss.dw.services.DefaultImportReceiptService.getLatestOneByImportType(DefaultImportReceiptService.java:26)
...
Run Code Online (Sandbox Code Playgroud)

或者,换句话说,CrudRepository相当于:

SELECT * FROM ImportReceipts ORDER BY timestamp DESC LIMIT 0,1;
Run Code Online (Sandbox Code Playgroud)

java mysql jpa spring-data

4
推荐指数
1
解决办法
1万
查看次数

春季预定任务没有解雇

我正在自学Spring,目前正在执行计划任务,以下代码不会触发计划任务.

我相信它与我设置Spring上下文的方式有关,但这只是猜测 - 我正在尝试学习Spring,所以请原谅荒谬的while循环.

Application.java:

package hello;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {

    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext rootContext =
                        new AnnotationConfigApplicationContext();

        rootContext.register(RootContextConfiguration.class);
        rootContext.refresh();

        while(rootContext != null) {
            try {
                Thread.sleep(2500);
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            System.out.println("Loop\n");
        }

        rootContext.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

RootContextConfiguration.java:

package hello;

import java.util.concurrent.Executor;

import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

@Configuration
@EnableScheduling
@EnableAsync(
        mode = …
Run Code Online (Sandbox Code Playgroud)

java spring scheduled-tasks spring-scheduled

2
推荐指数
1
解决办法
2万
查看次数

防止内部事务回滚外部事务

我有一个有点复杂的事务,它创建或不创建许多不同类型的实体.如果由于验证错误而无法创建其中一个实体,我想简单地捕获ConstraintValidationError并继续(允许在同一事务中创建的任何其他实体成功保存).

我可以成功地执行此操作,但验证错误仍然标记我的整个回滚事务,我不想要.

我尝试更改单个验证方法,导致ConstraintValidationError具有:

@Transactional(propagation = Propagation.NOT_SUPPORTED)
Run Code Online (Sandbox Code Playgroud)

强制一个新的事务,认为它只会标记新的内部事务回滚,但似乎并非如此.

调用类标有:

@Transactional(noRollbackFor=ConstraintViolationException.class)
Run Code Online (Sandbox Code Playgroud)

但是如果ConstraintViolationException在被调用的方法中并且我不希望将它添加到被调用的方法,这没有用.

做这样的事情的正确方法是什么?

(如果需要代码,请告诉我 - 示例有点复杂.)

编辑(2014年5月26日):

当我尝试

progration = Propagation.REQUIRES_NEW
Run Code Online (Sandbox Code Playgroud)

我看到结果没有变化.此特定日志来自有意尝试使用空描述保存"部门"实体对象的测试,该描述无效:

11:46:43.599 [main] DEBUG org.springframework.transaction.annotation.AnnotationTransactionAttributeSource - Adding transactional method 'DefaultCourseManager.saveDepartment' with attribute: PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT; ''
11:46:43.599 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
11:46:43.599 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Found thread-bound EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@3a90c13c] for JPA transaction
11:46:43.599 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Suspending current transaction, creating new transaction with name [edu.ucdavis.dss.dw.site.DefaultCourseManager.saveDepartment]
11:46:43.600 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Opened new EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@67b355c8] …
Run Code Online (Sandbox Code Playgroud)

java hibernate transactions spring-data

2
推荐指数
1
解决办法
2656
查看次数