【发布时间】:2015-01-28 07:59:10
【问题描述】:
我一直在努力实现以下目标......
- 用户有很多联系人
- 联系人属于所有者,即用户
- 创建联系人不仅限于用户(例如,提交表单的非用户以及登录时添加新联系人的用户都可以创建联系人)。
目前,当我以用户身份创建联系人时,联系人的 owner_id 和 user_id 一直为零。
以下是我目前的情况...我犯了什么明显的错误可以快速解决它们吗?
模型
联系模特:
class Contact < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
belongs_to :user
validates :email, :presence => {:message => 'Email cannot be blank'}
end
用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :leadhooks
has_many :contacts, :foreign_key => 'owner_id'
# validates_formatting_of :website, using: :url
# validates_formatting_of :phone, using: :us_phone
end
控制器
contacts_controller.rb
class ContactsController < InheritedResources::Base
before_action :set_contact, only: [:show, :edit, :update, :destroy]
def index
@user = current_user
@contacts = @user.contacts.order("created_at DESC")
end
def show
end
def new
@contact = Contact.new
end
def edit
end
def create
@contact = Contact.new(contact_params)
respond_to do |format|
if @contact.save
format.html { redirect_to @contact, notice: 'Contact was successfully created.' }
format.json { render :show, status: :created, location: @contact }
else
format.html { render :new }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @contact.update(contact_params)
format.html { redirect_to @contact, notice: 'Contact was successfully updated.' }
format.json { render :show, status: :ok, location: @contact }
else
format.html { render :edit }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
def destroy
@contact.destroy
respond_to do |format|
format.html { redirect_to contacts_url, notice: 'Contact was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_contact
@contact = Contact.find(params[:id])
end
def contact_params
params.require(:contact).permit(:name, :user_id, :email, :owner_id)
end
end
架构
create_table "contacts", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.string "email"
t.integer "user_id"
t.integer "owner_id"
end
add_index "contacts", ["owner_id"], name: "index_contacts_on_owner_id", using: :btree
add_index "contacts", ["user_id"], name: "index_contacts_on_user_id", using: :btree
我一直在关注这里给出的答案...
How would you model contact list with self-reference and category?
但是,不知道为什么 user_id 和 owner_id 没有应用于联系人以及如何不将联系人的创建限制为仅用户(例如,允许通过非用户提交的表单创建联系人网页上的用户)
非常感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails ruby model-view-controller associations