Rails: FriendlyId gem not working - ruby-on-rails-3

I was trying to install gem FriendlyId. I am following railscast: 314-pretty-urls-with-friendlyid. It seems pretty easy to install. But not working for me.
Here are the steps I did:
added gem "friendly_id", "~> 4.0.9" in Gemfile
I then ran bundle install command
Then modified my product model to this:
class Product < ActiveRecord::Base
extend FriendlyId
friendly_id :name
attr_accessible :name, :product_code, :recipe, :selling_price, :servings, letsrate_rateable "quality", "packaging", "hygiene" , "service", "price"
validates :name, :presence => true
class << self
def search(params)
if params[:search]
products = Product.published.includes(:product_sub_categories)
end
end
end
end
Still it is showing 'id':
http://localhost:3000/products/9
As per railscasts it should show product name. But it is not. I individually install gem but no effect.
Can anybody tell what I am missing?

Not sure why this is not mentioned in Guide, but try:
alias_attribute :to_param, :slug
This works because to_param method allows to customise the id part of URL. And here you are assigning that part to friendly_id generated URL.
Another solution
I am not sure if this is implemented inside friendly_id, but I did this:
class Product < ActiveRecord::Base
def self.find(id_or_slug)
case id_or_slug
when String
find_by_slug id_or_slug
else
super id_or_slug
end
end
end

Related

undefined method `selector' for #<ActiveRecord::Relation:0xbb8710c> when using mongoid to save a record

undefined method `selector' for #<ActiveRecord::Relation:0xbb8710c>
I am getting this error while trying to execute the follwoing code:
c = Content.first
c.is_processed = true
c.save # or c.update_attributes(:is_processed => true)
My Content model looks like this:
class Content
include Mongoid::Document
field :username
field :name
filed :is_processed, :type => Boolean
belongs_to :language
has_many :translations
end
I am using Mongoid 2.4, bson_ext 1.5, Ruby 1.9.2, Rails 3.2.5
I found the mistake. My Content model had this line:
has_many :translations
I had migrated the content model from ActiveRecord to Mongoid. But, all the other tables are still in ActiveRecord. The has_many was referring to a ActiveRecord model. This caused the issue. I commented the line and now update is working fine.

Setup rails3 text_field for rocket_tag tag list

This is the first time I've tried to add a tags field to a form so bear with me.
I'm using:
rails 3.2.8
Postgres 9.1
rocket_tag 0.5.6
squeel 1.0.9
I have installed the rocket_tag gem and run the various commands
rails generate rocket_tag:migration
rake db:migrate
rake db:test:prepare
to set everything up.
I've amended my Meeting model:
*Adding :tags and :tag_list to attr_accessible
*Adding attr_taggable :tags
*I've added a virtual attribute for displaying the tag list in the form field:
def tag_list
self.tags.join(",")
end
def tag_list=(new_tags)
self.tags = new_tags.split(/,[\s]*/).reject(&:empty?)
end
*I have added f.text_field :tag_list to my form view
This left me with my list page not working though. It said Association named 'taggings' was not found; perhaps you misspelled it?
User
has_many :meetings
has_many :meeting_dates, :through => :meetings
Meeting
belongs_to :user
has_many :meeting_dates
Meeting Dates
belongs_to :meeting
In my list page I list meeting dates using:
user_meeting_dates = #user.meeting_dates.includes(:meeting => :user)
To get past the taggings error I seem to need to have the following in my Meeting Dates model:
has_many :taggings, :through => :meeting
has_many :tags, :through => :taggings
Can someone explain why I need these here and whether there's a way to tidy this up any more, it doesn't seem like it's right.
Should it not be possible to do something like:
user_meeting_dates = #user.meetings.meeting_dates
Thanks
Once I've got this working correctly I can move on to apply Select2 to my tags field but I need to get it working just from a plain text field first.

Mongoid code not working in production

The following code works in development like a charm, but in production no update is ever issued to the database. Basically I am trying to update a collection element that is nested 3 levels deep ..
def set_collection_value
#article = Article.find(params[:id])
#article.highlights.items.find(params[:item_id])
item.update_attributes(params[:values])
render :json => item
end
The model Article in question looks like this:
class Article
include Mongoid::Document
embeds_one :highlight, class_name: 'Highlight'
end
highlight.rb
class Highlight
includes Mongoid::Document
embedded_in :article
embeds_many :items, class_name: 'HighlightElement'
end
highlight_item.rb
class HighlightElement
include Mongoid::Document
embedded_in :highlight
field :title, type: String
field :teaser, type: String
field :image, type: String
field :body, type: String
attr_accessible :title, :teaser, :image, :body
end
The funny thing here is that even when I run webrick locally in production mode it works like a charm. Only once I deploy to my ubuntu server running mongodb v1.2.2 the above code silently does nothing.
I even went as far as to copy my environments/development.rb onto my environments/production.rb hoping to fix the issue.. but to no avail..
Any ideas? I am running rails 3.2.7 with mongoid 3.0.3
It would also be helpful if someone could point out how to make the moped/mongoid debug log messages show up in production.log. I configured Debugging as described in the logs - but these debug messages are only visible when running rails s - not in production.log
Solved it myself..
Turns out Mongodb 1.2.2 from the official Ubuntu repository sources was the problem.
After updating to 2.0.5 everything worked again correctly.

Using factory_girl_rails with Rspec on namespaced models

I have a web service that serves Ads to several different clients. The structure of the Ad varies between clients, and therefore, I am using namespaces for my models and controllers by the client name to differentiate between Ads. From the high level, it looks like this:
'app/models/client1/ad.rb'
class Client1::Ad < ActiveRecord::Base
attr_accessible :title, :description
end
'app/models/client2/ad.rb'
class Client2::Ad < ActiveRecord::Base
attr_accessible :title, :description, :source
end
In reality, these models are more complex and have associations, but that is not the point.
I am writing some unit tests using rspec-rails 2.4.0 and factory_girl_rails 1.0.1, and all of my factories work great. However, I am not able to define factories for the namespaced models. I've tried something like:
Factory.define :client1_ad, :class => Client1::Ad do |ad|
ad.title "software tester"
ad.description "Immediate opening"
end
and
Factory.define :client2_ad, :class => Client2::Ad do |ad|
ad.title "software tester"
ad.description "Immediate opening"
ad.source "feed"
end
It didn't do the job. I looked around, but every single example that I saw was using non-namespaced models. Anyone have any ideas? Any input is greatly appreciated.
I have a minimal working example here, maybe you could use it to pinpoint where your problem is. The comment you left on dmarkow's answer suggests to me that you have an error someplace else.
app/models/bar/foo.rb
class Bar::Foo < ActiveRecord::Base
end
*db/migrate/20110614204536_foo.rb*
class Foo < ActiveRecord::Migration
def self.up
create_table :foos do |t|
t.string :name
end
end
def self.down
drop_table :foos
end
end
spec/factories.rb
Factory.define :foo, :class => Bar::Foo do |f|
f.name 'Foooo'
end
*spec/models/foo_spec.rb*
require 'spec_helper'
describe Bar::Foo do
it 'does foo' do
foo = Factory(:foo)
foo.name.should == 'Foooo'
end
end
Running the test:
$ rake db:migrate
$ rake db:test:prepare
$ rspec spec/models/foo_spec.rb
.
Finished in 0.00977 seconds
1 example, 0 failures
Hope it helps.
I think maybe FactoryGirl changes since this answer was posted. I did to make it work
Factory.define do
factory :foo, :class => Bar::Foo do |f|
f.name 'Foooo'
end
end
With the current latest version of FactoryGirl (4.5.0), this is the syntax:
FactoryGirl.define do
factory :client1_ad, class: Client1::Ad do |f|
f.title "software tester"
f.description "Immediate opening"
end
end
Notice that client1_ad can be whatever name you want coz we already force identifying its class name.
I found this question looking into a related issue with FactoryGirl and after a little reading of the source I figured out I could solve my problem by renaming my factories.
When I had model classes that were namespaced inside modules, eg: Admin::User I should have been defining my factories like this:
factory :'admin/user', class: Admin::User do
#...
end
Rather than:
factory :admin_user, class: Admin::User do
#...
end
Maybe this little tidbit of info might help someone someday. The specifics of my issue was that I was trying to use build(described_class) to build instances from factories in my RSpec specs and this works just fine with un-namespaced classes but not with classes inside modules. The reason is that internally when looking up factories FactoryGirl will use ActiveSupport's underscore helper to normalise the factory name.
Have you tried passing the actual class, rather than a string with the class name:
Factory.define :client1_ad, :class => Client1::Ad do |ad|

model missing required attr_accessor for 'photo_file_name' when uploading with paperclip and S3 on heroku

Setting up paperclip with S3 in my linux dev environment was a snap -- everything works out of the box. However, I can't get it to work on Heroku.
When I try to do an upload, the log shows:
Processing ItemsController#create (for 72.177.97.9 at 2010-08-26 16:35:14) [POST]
Parameters: {"commit"=>"Create", "authenticity_token"=>"0Hy3qvQBHE1gvFVaq32HMy2ZIopelV0BHbrSeHkO1Qw=", "item"=>{"photo"=>#<File:/home/slugs/270862_4aa601b_4b6f/mnt/tmp/RackMultipart20100826-6286-1256pvc-0>, "price"=>"342", "name"=>"a new item", "description"=>"a new item", "sold"=>"0"}}
Paperclip::PaperclipError (Item model missing required attr_accessor for 'photo_file_name'):
I found one blog post that referenced this error, and it said to add this to my model:
attr_accessor :photo_file_name
attr_accessor :photo_content_type
attr_accessor :photo_file_size
attr_accessor :photo_updated_at
That does indeed make the model missing required attr_accessor for 'photo_file_name' error go away, but it still doesn't work. See my other question for details. As I have figured out that with the attr_accessor lines added to my model the uploads fail even on my dev system, I suspect that is not the right answer.
Found the problem: needed to update the database.
heroku run rake:db:migrate
heroku restart
I had done what I thought would have accomplished the same thing already:
heroku rake db:schema:load
but perhaps that doesn't work or something went wrong in the process.
Error like this occurs if you create wrong column type in migration. When you define new table migration for paperclip, you need to specify t.attachment :name insted of t.string :name. Or add_attachment :table, :name when you add new paperclip column in existed table. And now you don't need to add these attributes in attr_accessor in model.
Well, this message seems to be because the columns it's missing. Try create a migration creating the columns:
class AddPhotoToEvent < ActiveRecord::Migration
def change
add_column :events, :photo_file_name, :string
add_column :events, :photo_content_type, :string
add_column :events, :photo_file_size, :integer
add_column :events, :photo_updated_at, :datetime
end
end
This work for me, here i have a table events with photo