Reputation: 406
I am running Rails 4.0. Ruby 2.0
For signing up, I only ask users to provide me with there email in the new page.
In the update action, I then ask users for their name.
When listing users in the Index action, I only want to show users have updated their name.
I know I need to scope based on if users have updated their name.
User Model
scope :name, where(name: true)
User Controller
def index
@users = User.name
end
Error
undefined method `gsub' for #
I Think the issue is the way, I am calling the scope. I might need to use exists?
Any help is greatly, appreciated. Thank you.
Upvotes: 1
Views: 77
Reputation: 77786
Personally, just to be a little more conventional, I would use
class User < ActiveRecord::Base
scope :has_name, where("users.name != ''")
end
This way, when your model gets joined with another, you won't introduce a column ambiguity in the event multiple tables have a name
column
Consider this example
$ rails new app
$ cd app
$ rails g resource User name:string company_id:integer
$ rails g resource Company name:string
$ rake db:migrate
Our models
class User < ActiveRecord::Base
belongs_to :company
scope :has_name, where("name != ''")
end
class Company < ActiveRecord::Base
has_many :users
end
A problem
$ rails c
irb> User.has_name.join(:company)
Oh noes!
User Load (0.4ms) SELECT "users".* FROM "users" INNER JOIN
"companies" ON "companies"."id" = "users"."company_id" WHERE
(name != '')
SQLite3::SQLException: ambiguous column name: name: SELECT
"users".* FROM "users" INNER JOIN "companies" ON
"companies"."id" = "users"."company_id" WHERE (name != '')
ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous
column name: name: SELECT "users".* FROM "users" INNER JOIN
"companies" ON "companies"."id" = "users"."company_id" WHERE
(name != '')
Let's fix the scope
class User < ActiveRecord::Base
belongs_to :company
scope :has_name, where("users.name != ''")
end
Re-run our query
irb> reload!
irb> User.has_name.join(:company)
Proper output
User Load (0.1ms) SELECT "users".* FROM "users" INNER JOIN "companies"
ON "companies"."id" = "users"."company_id" WHERE (users.name != '')
=> []
Upvotes: 3
Reputation: 781
You could use:
scope :with_name, where("name <> ''")
Though the above doesn't tell you if they've actually modified their name, just that it isn't blank. If you wanted to track the name column for changes, you could use something like the PaperTrail gem for this.
Based on additional feedback, I'd recommend:
scope :with_name, where("users.name != ''")
Upvotes: 1