, to_param는 URL이Ruby on Rails에서 to_param()을 변경하면 부작용이 생기며이를 변경하는 데 어떤 방법을 사용할 수 있습니까? 어떤 책에서
http://www.mysite.com/stories/1-css-technique-blog
대신 그래서 URL이 더 많은 검색 엔진입니다
http://www.mysite.com/stories/1
입니다 그래서
class Story < ActiveRecord::Base
def to_param
"#{id}-#{name.gsub(/\W/, '-').downcase}"
end
end
로 변경하는 것이 좋습니다 친한.
레일스의 다른 부분에서 to_param()을 사용할 필요가 없으므로이를 변경하면 부작용이 생길 수 있습니다. 아니면 유일한 목적은 연결을위한 URL을 구성하는 것입니까?
또 다른 것은 URL 크기를 2k 미만으로 제한 할 필요가 없습니다. IE가 2k 이상이거나 어쩌면 2k 이상인 부분이 IE에서 무시되고 그래서 URL은 여전히 작동합니다. URL을 30 분 또는 40 자로 제한하는 것이 좋을 수도 있습니다.
http://www.mysite.com/stories/1-css-technique-blog
이 작동
로 to_param가 그런 식으로 변경하면 class User < ActiveRecord::Base
def to_param # overridden
name
end
end
는 다음 링크가 실제로 작동하지 않습니다,하지만
: 또한, to_param의 ri
문서
http://www.mysite.com/stories/css-technique-blog
ID가 누락되어 작동하지 않습니다. to_param 메소드를 변경하는 다른 방법이 있습니까?
업데이트 : 두 번째 생각에는, 어쩌면
http://www.mysite.com/stories/css-technique-blog
유사한 제목의 많은 웹 페이지가있는 경우에 잘 작동하지 않습니다. 하지만
http://www.mysite.com/user/johnchan
이 적용됩니다. params [: id]가 "johnchan"일까요? 그러면 사용자를 얻으려고
user = User.find_by_login_name(params[:id])
을 사용합니다. 따라서 URL에서 param을 사용하는 방법에 따라 다릅니다. 당신이 당신의 URL이 더 많은 검색 엔진 친화적 확인하려면
C:\ror>ri ActiveRecord::Base#to_param
-------------------------------------------- ActiveRecord::Base#to_param
to_param()
------------------------------------------------------------------------
Returns a String, which Action Pack uses for constructing an URL to
this object. The default implementation returns this record's id as
a String, or nil if this record's unsaved.
For example, suppose that you have a User model, and that you have
a +map.resources :users+ route. Normally, +user_path+ will
construct a path with the user object's 'id' in it:
user = User.find_by_name('Phusion')
user_path(user) # => "https://stackoverflow.com/users/1"
You can override +to_param+ in your model to make +user_path+
construct a path using the user's name instead of the user's id:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
user = User.find_by_name('Phusion')
user_path(user) # => "https://stackoverflow.com/users/Phusion"
230 개의 질문을하고 30 % 만 답변을 수락했습니다. –