我有一個帳戶模型和帳戶經理(用戶)的應用程序。rails通過他們的電子郵件更新用戶的記錄
我希望帳戶經理能夠通過輸入他們的電子郵件將其他用戶添加到帳戶。
應將客戶經理的賬戶ID添加到新用戶的記錄中。
我的模型看起來像
class Account < ActiveRecord::Base
has_many users
...
end
class User < ActiveRecord::Base
belongs_to account
...
end
在控制檯這是相當簡單的。
u = User.find(2)
u.update_attributes(account_id: 1)
但我不知道如何在網站上做到這一點。
我有下面的部分呈現罰款,但當我把一個電子郵件在框中沒有任何反應。
我得到的消息,用戶沒有添加。
<h4>Add User</h4>
<div class = "row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(:add_user, url: add_users_path) do |f| %>
<%= f.hidden_field @account = Account.find(params[:id]) %>
<%= f.label :email %>
<%= f.email_field :email, class:'form-control' %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
我並不想/需要路由到例如另一頁「網址:add_users_path」,但沒有該行的代碼中斷,也不會呈現。
我說這user.rb
def add_user_to_account
update_attribute(:account_id)
end
我也創造了該控制器
class AddUsersController < ApplicationController
before_action :get_user, only: [:edit, :update]
def new
end
def edit
end
def create
@user = User.find_by(email: params[:email])
if @user
@user.add_user_to_account
flash[:info] = "Added User to Account"
redirect_to accounts_url
else
flash[:danger] = "User NOT Added"
redirect_to accounts_url
end
end
def update
if params[:user][:account_id].empty?
@user.errors.add(:account_id, "can't be empty")
render 'edit'
elsif @user.update_attributes(user_params)
log_in @user
flash[:success] = "Account Updated"
redirect_to @user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:account_id, :user_id)
end
def get_user
@user = User.find_by(email: params[:email])
end
end
我在正確的軌道上?有一個更好的方法嗎?
更新:添加的架構
create_table "accounts", force: :cascade do |t|
t.string "name"
t.integer "account_manager_id"
t.integer "subscription_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "password_digest", null: false
t.string "remember_digest"
t.string "email", null: false
t.string "activation_digest"
t.boolean "activated"
t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "access_granted"
t.boolean "requested_access"
t.string "slug"
t.integer "account_id"
end
會是可能的,你可以分享一些架構有問題的車型。 謝謝 – MZaragoza
@MZaragoza我更新了模式 – railsie