rails4 activeRecord error - ruby-on-rails-3

SyntaxError: C:/Users/NEBELYN/Desktop/cms/simple_cms/app/models/subject.r
b:3: syntax error, unexpected =>, expecting ')'
scope :visible, lambda { where (:visible => true) }
^
C:/Users/NEBELYN/Desktop/cms/simple_cms/app/models/subject.rb:4: syntax e
rror, unexpected =>, expecting ')'
scope :invisible, lambda { where (:visible => false) }
^
C:/Users/NEBELYN/Desktop/cms/simple_cms/app/models/subject.rb:10: syntax
error, unexpected keyword_end, expecting '}'
from C:/Ruby200/lib/ruby/gems/2.0.0/gems/activesupport-4.0.2/lib/
active_support/dependencies.rb:424:in `load'
from C:/Ruby200/lib/ruby/gems/2.0.0/gems/activesupport-4.0.2/lib/
active_support/dependencies.rb:424:in `block in load_file'
from C:/Ruby200/lib/ruby/gems/2.0.0/gems/activesupport-4.0.2/lib/
active_support/dependencies.rb:616:in `new_constants_in'
when my subject.rb file looks like this
class Subject < ActiveRecord::Base
scope :visible, lambda { where (:visible => true) }
scope :invisible, lambda { where (:visible => false) }
scope :sorted, lambda {order("subjects.position ASC")}
scope :newest_first, lambda{ order("subjects.created_at DESC")}
scope :search. lambda { |query|
where (["name like ?", "%#{query}%"])
}
end
when i run this command on the rails console "Subject.visible" pls help

You cannot put spaces between where and (.
scope :visible, lambda { where (:visible => true) } # bad
scope :visible, lambda { where(:visible => true) } # good

Remove the space between where and the open paranthesis
class Subject < ActiveRecord::Base
scope :visible, lambda { where(:visible => true) }
scope :invisible, lambda { where(:visible => false) }
scope :sorted, lambda {order("subjects.position ASC")}
scope :newest_first, lambda{ order("subjects.created_at DESC")}
scope :search. lambda { |query|
where(["name like ?", "%#{query}%"])
}

Related

Rails 3 parent and child association scopes optimization

I have a parent has many children association in my project. I'm trying to get a list of children that have certain flags set from the parent when I render it.
For example this:
# some_controller
#thread = Thread.includes(:posts)
render :json => #thread.posts.as_json
will return something like
[
{
"id" => 1,
"posts" => [
{ "id" => 1, "flagged" => true },
{ "id" => 2, "flagged" => false }
]
}
]
I'm trying to get the output to be like this
[
{
"id" => 1,
"posts" => [
{ "id" => 2, "flagged" => false }
]
}
]
i.e.: only posts that are not flagged should be rendered.
I've overridden the as_json method in my model in order to do this as such:
def as_json(options = {})
...
{
:id => self.id,
:posts => self.posts
}
...
end
I realize that I can define a scope in the Posts model and use :posts => self.posts.not_flagged, but this causes an extra database query for every thread in my database (makes everything slow).
Aside from a default_scope on the Posts model how else could I solve this extra query problem?
I figured it out a bit after I posted.
I can add a scope in my Parent model to do this:
# Thread.rb
...
has_many :unflagged_posts, :class_name => "Post", :conditions => { :flagged => false }
...
And in my controller:
# some_controller
#threads = Thread.includes(:unflagged_posts)
This way ActiveRecord eager loads the posts with the flagged condition, rather than doing an extra query for each post!

NHibernate 3.2 Mapping by code - can you map to private fields for Id and bag?

e.g.
this.Bag(
r => "privatefieldtomap",
map =>
{
map.Access(Access.Field);
map.Table("table");
map.Key(k => k.Column("foreignkey"));
},
r => r.Element(m => m.Column("columntomap")));
public SomeType()
{
this.Id(p => "privateidfield", Access(Access.Field));
this.Table("SomeTable");
this.Property(p => p.SomeProperty);
}
both throw an exception "expression expected; constant found"
We could do this using xml mapping.
Answer here https://groups.google.com/forum/#!topic/nhusers/wiH1DPGOhgU turns out there is an overload that accepts a string as first parameter whereas I was using a lambda expression.

Thinking Sphinx Scope Returning mix of Results and "blanks"

Controller:
#sites = Site.inspections_enabled_controllers_search.search("test")
#sites.each do |s|
if s == nil
puts "WHAT THE ...?"
end
ap s #print out the site
end
Model:
has_many :inspections_enabled_controllers,
:class_name => 'Controller',
:conditions => ['controllers.inspections_enabled = ?', true]
sphinx_scope(:inspections_enabled_controllers_search) {
{
:joins => :inspections_enabled_controllers
}
}
Returns:
#<Site:0x000000114618b8> {
:id => 156,
:name => "Test Site"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x000000111c41a0> {
:id => 213,
:name => "TestRail V1.5 - SmartLine"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x00000011461200> {
:id => 220,
:name => "Activation Testing"
}
NOTICE the total of SEVEN "-" which are simply empty items in an array.
This worked for me
#sites = Site.inspections_enabled_controllers_search.search("test", :retry_stale => 1)
Reference:
http://pat.github.com/ts/en/searching.html#nils

Passing argument to decorator from controller in Rails using Draper

I couldn't figure out how to pass an argument to a decorator from a controller:
The decorator:
def as_json(options = nil)
{
:name => user.name,
:dob => user.dob
:created_at => user.created_at,
:url => user
}
end
The controller:
format.json { render :json => UserJsonDecorator.new(#user)}
Just passing an extra argument to the new method does not work:
UserJsonDecorator.new(#user,options)
Any ideas?
I was basically using it wrong.
correct form to pass additional arguments is:
UserJsonDecorator.new(#user).to_json(options)

Rails 3: How do I validate to allow blanks ("") but not nil (NULL in database)

In an ActiveRecord (or ActiveModel) I would like the following spec to pass
it { should allow_value("").for(:my_string) }
it { should_not allow_value(nil).for(:my_string) }
I have tried
validates :my_string, {
:length => { :in => 0..255 },
:presence => true,
:allow_blank => true,
:allow_nil => false,
}
and also
validates :my_string, {
:length => { :in => 0..255 },
:allow_blank => true,
:allow_nil => false,
}
But either it allows both "" and nil or none of them.
This works for me
validates :my_string, length: { in: 0..255, allow_nil: false }
If you just want to validate that the field is not null, but don't care about blank/empty strings, this works:
validates :my_string, length: { minimum: 0, allow_nil: false, message: "can't be nil" }
You can try doing:
validates :my_string, exclusion: { in: [nil]}
It is part of the validations themselves in ActiveRecord.
I've tried the others and all of them are very compliated or allow nil too.
You might need to do a custom validation for this:
validates :my_string, :length => { :in => 0..255 }
validate :my_string_is_valid
def my_string_is_valid
self.errors.add :base, 'My string can not be nil' if self.my_string.nil?
end
You can create a simple custom validator (placed in app/validators dir)
class NotNilValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << "must not be nil" if value.nil?
end
end
and then
validates :my_string, not_nil: true
Or maybe:
validates :my_string, :length => { :in => 0..255 }, :allow_nil => false
Seems that allow_nil does not override allow_blank.
So you better no specify allow_blank
This works for me:
validates_exclusion_of :my_string, in: [nil]