0

I have a comments scaffold and a movies scaffold.

Users can comment on movie in this path /movies/the-social-network/comments/new

My issue is that the comments use movie_id to work and to link with the movies.

So what I'm asking is how to pass the-social-network as the movie_id?

PS: Im using Friendly Id 4

4

2 回答 2

1

首先,由于您想Movie通过“slug”之类的方式进行查找the-social-network,因此您需要扩展FriendlyId并告诉它将 参数id化为一个名为 的属性slug。通过:slugged如下传递来做到这一点:

# app/models/movie.rb
class Movie < ActiveRecord::Base
    extend FriendlyId
    friendly_id :title, use: :slugged
end

然后,创建一个迁移来存储slug对象Movie

# in console
rails g migration add_slug_to_movies slug:string

修改迁移文件以添加slug为索引:

# change migration file
class AddSlugToMovies < ActiveRecord::Migration
    def change
        add_column :movies, :slug, :string
        add_index :movies, :slug
    end
end

最后,您需要为数据库中的所有现有电影创建一个 slug。您可以通过逐一保存每部电影来做到这一点:

# in Rails console 
Movie.find_each(&:save)

完成此操作后,您应该能够在Movie类似于/movies/the-social-network/comments/new.

查看此 Railscast以获取更多详细信息和示例,包括确保在数据库中更改标题时正确更新对象的 slug。

于 2013-06-12T17:49:10.240 回答
0

您可以使用to_param。例如,如果movie_name是 'the-social-network',这将起作用:

class Movie < ActiveRecord::Base
  def to_param
    movie_name
  end
end
于 2013-06-12T06:12:02.183 回答