标签: rails-activerecord

rails try方法抛出NoMethodError?

为什么尝试抛出错误?不是打败了整个目的吗?也许只是在控制台?

ruby-1.9.2-p180 :101 > User.first.try(:something)
NoMethodError: undefined method `something' for #<User:0x000001046ad128>
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activemodel-3.0.10/lib/active_model/attribute_methods.rb:392:in `method_missing'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.10/lib/active_record/attribute_methods.rb:46:in `method_missing'
    from (irb):101
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
Run Code Online (Sandbox Code Playgroud)

编辑:

谢谢你们,现在我明白了.

有没有办法在不使用的情况下做我想做的事情respond_to?,这样User.try(:something)返回nil而不是抛出错误?

ruby-on-rails nomethoderror rails-activerecord

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

Rails 3.1:无法在添加它的同一个迁移中写入列

我有一个可以正常运行的add_column迁移.但是,在运行它并启动控制台后,我会发现first_name和last_name列完全为空.我尝试使用save!而且它具有相同的效果 - 没有报告错误.这是原始的:

class UserAddFirstNameAndLastName < ActiveRecord::Migration
  def change
    # add column first name, last name string
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string

    User.all.each do |u|
      u.first_name = 'first name'
      u.last_name = 'last name'
      u.save
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我还认为这可能是一些类加载问题,所以我插入行User以强制用户类在循环之前重新加载.没有骰子.

当我将其拆分为两次迁移时,实现了期望的效果.有人对此有解释吗?我发誓我甚至在过去迁移的同一个项目中做过这个.

其他说明:设计用户引擎,attr_accessible在运行迁移之前将新列添加到User类中.

activerecord ruby-on-rails rails-migrations ruby-on-rails-3 rails-activerecord

23
推荐指数
1
解决办法
4927
查看次数

如何将两个范围与OR组合

我有一个标签Feed和一个朋友Feed.我想结合这两个并构建最终的"全部"提要.

对于朋友饲料:

class Post < ActiveRecord::Base
  scope :friendfeed, lambda{|x| followed_by}

  def self.followed_by(user)
    where("user_id IN (?) OR user_id = ?", user.watched_ids, user.id)
  end
end
Run Code Online (Sandbox Code Playgroud)

对于标签Feed:

class Post < ActiveRecord::Base
  scope :tagfeed, lambda{|x| infatuated_with}

  def self.infatuated_with(user)
    joins(:attachments).where("attachments.tag_id IN (?)", user.tags).select("DISTINCT pages.*")
  end
end
Run Code Online (Sandbox Code Playgroud)

我会从控制器中调用这样的东西(我使用Kaminari宝石进行分页):

@tag_feed = Post.tagfeed(current_user).page(params[:page]).per(21)
@friend_feed = Post.friendfeed(current_user).page(params[:page]).per(21)
Run Code Online (Sandbox Code Playgroud)

现在我想要一个通用的饲料,但我迷路了.范围用于缩小范围,但在这种情况下,我正在尝试进行OR操作.做像这样的事情

@mother_of_all_feed = @tag_feed + @friend_feed
Run Code Online (Sandbox Code Playgroud)

将是多余的,我将无法控制出现在单个页面上的帖子数量.我该怎么做呢?谢谢!

顺便说一句,对于标签我有这样的关联设置:

class Post < ActiveRecord::Base
  has_many :attachments
  has_many :tags, :through => :attachments
end

class Tag < ActiveRecord::Base
  has_many :attachments
  has_many :posts, :through => :attachments
end …
Run Code Online (Sandbox Code Playgroud)

database-design ruby-on-rails ruby-on-rails-3 rails-activerecord

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

将参数添加到范围

我有一个ActiveRecord查询,例如:

@result = stuff.limit(10)
Run Code Online (Sandbox Code Playgroud)

stuff是一个活动的记录查询,其中where子句,order by等等...

现在我想为什么要将这样的魔法数字传递给控制器​​?那么你认为定义"limit(10)"的范围并使用它是一个好习惯吗?语法怎么样?

ruby-on-rails ruby-on-rails-3.2 rails-activerecord

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

弃用警告:危险查询方法:ActiveRecord中的随机记录> = 5.2

到目前为止,从数据库获取随机记录的"常见"方法是:

# Postgress
Model.order("RANDOM()").first 

# MySQL
Model.order("RAND()").first
Run Code Online (Sandbox Code Playgroud)

但是,在Rails 5.2中执行此操作时,它会显示以下Deprecation警告:

DEPRECATION WARNING:使用非属性参数调用的危险查询方法(其参数用作原始SQL的方法):"RANDOM()".Rails 6.0中不允许使用非属性参数.不应使用用户提供的值调用此方法,例如请求参数或模型属性.可以通过将它们包装在Arel.sql()中来传递已知安全值.

我对Arel并不熟悉,所以我不确定解决这个问题的正确方法是什么.

ruby-on-rails rails-activerecord deprecation-warning ruby-on-rails-5.2

23
推荐指数
2
解决办法
3373
查看次数

如何在Rails中使数据库字段为只读?

我有一个带有某个字段的数据库表,一旦插入数据库就不可能更新.如何告诉我的模型它不应该允许更新某个字段?

ruby-on-rails rails-activerecord

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

无论如何撤消rails控制台中的activerecord删除?

我在脚本/控制台中犯了一个令人难以置信的可怕错误:

user.delete
Run Code Online (Sandbox Code Playgroud)

有没有办法在同一个脚本/控制台会话中撤消它?

ruby-on-rails rails-activerecord

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

新数据不会持久到Postgres上的Rails数组列

我有一个带有文本类型的朋友列的用户模型.运行此迁移以使用postgres的数组功能:

add_column    :users, :friends, :text, array: true
Run Code Online (Sandbox Code Playgroud)

用户模型具有以下方法:

def add_friend(target)
  #target would be a value like "1234"
  self.friends = [] if self.friends == nil
  update_attributes friends: self.friends.push(target)
end
Run Code Online (Sandbox Code Playgroud)

以下规范通过,直到我user.reload在调用后添加#add_friend:

it "adds a friend to the list of friends" do
  user = create(:user, friends: ["123","456"])
  stranger = create(:user, uid: "789")
  user.add_friend(stranger.uid)
  user.reload #turns the spec red
  user.friends.should include("789")
  user.friends.should include("123")
end
Run Code Online (Sandbox Code Playgroud)

这也发生在开发中.模型实例已更新并在数组中具有新的uid,但是一旦在不同的操作中重新加载或重新加载用户,它将恢复到add_friend调用方法之前的状态.

使用Rails 4.0.0.rc2和pg 0.15.1

这可能是什么?

arrays postgresql ruby-on-rails ruby-on-rails-4 rails-activerecord

22
推荐指数
2
解决办法
6092
查看次数

Rails counter_cache未正确更新

使用Rails 3.1.3,我试图弄清楚为什么我们的计数器缓存在通过update_attributes更改父记录ID时没有正确更新.

class ExhibitorRegistration < ActiveRecord::Base
  belongs_to :event, :counter_cache => true
end

class Event < ActiveRecord::Base
  has_many :exhibitor_registrations, :dependent => :destroy
end

describe ExhibitorRegistration do
  it 'correctly maintains the counter cache on events' do
    event = Factory(:event)
    other_event = Factory(:event)
    registration = Factory(:exhibitor_registration, :event => event)

    event.reload
    event.exhibitor_registrations_count.should == 1

    registration.update_attributes(:event_id => other_event.id)

    event.reload
    event.exhibitor_registrations_count.should == 0

    other_event.reload
    other_event.exhibitor_registrations_count.should == 1
  end
end
Run Code Online (Sandbox Code Playgroud)

此规范失败,表明事件上的计数器缓存未递减.

1) ExhibitorRegistration correctly maintains the counter cache on events
   Failure/Error: event.exhibitor_registrations_count.should == 0
     expected: 0
          got: …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails ruby-on-rails-3.1 rails-activerecord

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

Rails:使用where子句查找深层嵌套的关联

我有两个模型加入了has_many:通过关系:

class Publication < ActiveRecord::Base
  has_many :publication_contributors
  has_many :contributors, :through => :publication_contributors
end

class Contributor < ActiveRecord::Base
  has_many :publication_contributors
  has_many :publications, :through => :publication_contributors
end

class PublicationContributor < ActiveRecord::Base
  belongs_to :publication
  belongs_to :contributor
end
Run Code Online (Sandbox Code Playgroud)

(关于我的PublicationContributor模型的一些不寻常和重要的是它不仅仅有一对数据库ID,它还有一个名为contributor_type的字符串属性.这个字符串可能包含诸如"Author"或"Translator"或"Publisher"之类的角色.我不相信这是问题,但解决方案仍然必须考虑到它.)

我想找一个具有特定贡献者的出版物,如下所示:

Publication
  .joins(:publication_contributors =>  :contributor)
  .where(:publication_contributors => 
            {:contributor_type => "Author", 
             :contributor => {:name => params[:authors]}})
Run Code Online (Sandbox Code Playgroud)

一切正常,直到我进入嵌套:贡献者,此时SQL溅出:

Mysql2::Error: Unknown column 'publication_contributors.contributor' in 'where clause'
Run Code Online (Sandbox Code Playgroud)

它不是在寻找publication_contributors.contributor_id,而是在寻找不存在的publication_contributors.contributor.我在代码中做错了吗?我找不到像这样具有深层嵌套关联的where子句的任何其他示例.也许它甚至不可能?

更新:

生成的SQL

?[1m?[35mPublication Load (0.0ms)?[0m  SELECT `publications`.* FROM `publicati
ons` INNER JOIN `publication_contributors` ON `publication_contributors`.`public
ation_id` = `publications`.`id` INNER JOIN `contributors` …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails rails-activerecord

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