【发布时间】:2016-04-09 07:45:33
【问题描述】:
过去两周我正在学习 Angular。我认为使用前端框架真的很有趣,我没想到我必须创建 2 个单独的完整应用程序:)。我有一些问题要问你
- 管理有角度的模型连接的最佳方法是什么,例如 rails user.animals.where(...)
例如 我有用户模型,每个用户都有很多动物。 在我要显示的页面上 与用户动物的链接表和与所有动物的右表, 现在我向动物控制器做出两个承诺,一次是针对用户,一次是针对所有动物,它是查询数量的两倍,当我想添加一个表单来创建新动物时很难管理,因为我必须将新对象推送到两个模型数组中在角度
此外,当每只动物都可以有很多玩具,而用户只能添加另一个用户的一个玩具专业动物时,这变得非常复杂
我必须从 rails 控制器发送 json,包括动物玩具以及带有用户 ID 的数组,然后在视图中
ng-hide="(animal['users_ids'].includes(user.id)"
使用此解决方案,当我创建新模型时,我必须更新玩具模型和动物,是否可以更简单地完成?
- 当角度模型和轨道模型发生变化时,同步角度模型和轨道模型的最佳方法是什么?
我可以每隔 x 秒刷新一次页面,但这不是专业的。
-
我已将 rails 和 angular 配置为与 devise 和 oauth 一起使用。我的配置有效,但我不确定解决方案是否可靠和安全
Gemfile gem 'devise' gem 'omniauth-facebook' gem 'omniauth-github' gem 'angular_rails_csrf'
rails 生成设计:安装
设置现有的用户模型
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook, :github]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
设置设计初始化器
config.clean_up_csrf_token_on_authentication = true
设置 onniauth 初始化器
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['APP_ID'], ENV['APP_SECRET'],
scope: 'email,public_profile', info_fields: 'email,id,name'
end
设置路线
devise_for :users, :controllers => { :omniauth_callbacks => "sessions#create" }
get '/auth/:provider/callback', to: 'sessions#create'
会话控制器
def facebook
@account = User.from_omniauth(request.env["omniauth.auth"])
sign_in @account
render 'sessions/create', layout: false
end
def github
@account = User.from_omniauth(request.env["omniauth.auth"])
sign_in @account
render 'sessions/create', layout: false
end
app/views/sessions/create.html.erb
<p>This view will now self-destruct</p>
<script>
try {
window.opener.$windowScope.handlePopupAuthentication('<%= @provider %>', <%= @account.to_json.html_safe %>);
} catch(err) {}
window.close();
</script>
和角度配置
app/assets/templates/login.html.slim
div.page-header
h1 Log In
div class="btn dash-subs login-btn" ng-click="authNetwork('facebook')"
p Login With Facebook
app/assets/javascript/auth/authCtrl.js
angular.module('myAPP')
.controller('AuthCtrl', [
'$scope',
'$state',
'Auth',
function($scope, $state, Auth){
$scope.handlePopupAuthentication = function handlePopupAuthentication(network, account) {
$scope.$apply(function(){
window.location.reload()
});
}
$scope.authNetwork = function authNetwork(network) {
var openUrl = '/users/auth/' + network
window.$windowScope = $scope;
window.open(openUrl, "Authenticate Account", "width=500, height=500");
};
}])
【问题讨论】:
标签: ruby-on-rails angularjs devise