【发布时间】:2014-10-20 17:06:45
【问题描述】:
如何使用任何就地编辑 gem 示例:best_in_place,在 has_one 和/或 has_many 关系中编辑子模型的属性。
示例:(只是一个示例,不是实际的问题;用于解释。) 用户模型有许多目标(目标模型),每个目标都有一些属性。我如何使用 gem 'best_in_place' 从显示页面编辑这些属性。
在 Railscast 上的“就地编辑”http://railscasts.com/episodes/302-in-place-editing 中进行了尝试,但最终出现了诸如"undefined method :property for goal" 之类的错误,并且在模型类的现场尝试了@user.goal 无济于事。
实际代码如下。
我实际上是用它来编辑用户的个人资料属性,但类似的概念和错误..
用户.rb
class User < ActiveRecored::Base
has_one :profile, dependent: :destroy
after_create :build_profile
accepts_nested_attributes_for :profile
attr_accessible :email, :password, :password_confirmation, :profile_attributes
def build_profile
Profile.create(user_id: self.id)
end
end
个人资料.rb
class Profile < ActiveRecord::Base
attr_accessible :name. :address, :age
belongs_to :user
validates :name, presence: true, length: { maximum: 50 }
validates :address, :age, presence: true
end
Users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
@profile = self.build_profile
end
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
flash[:success] = "welcome, Thanks for Signing up"
redirect_to @user
else
render 'new'
end
end
end
Profiles_controller.rb
class ProfilesController < ApplicationController
def edit
@profile = Profile.find(params[:id])
end
def update
@profile = Profile.find(params[:id])
if @profile.update_attributes(params[:profile])
flash[:success] = "Profile Updated"
redirect_to @user
else
render 'edit'
end
end
def show
@user.profile = User.find(params[:id]).profile
end
def destroy
end
end
用户/show.html.erb
<% provide(:title, "Profile" ) %>
<h1><%= @user.profile.name %></h1>
<p>
<b> Address </b> <%= best_in_place @profile, :address, :path => user_profile_path(@user, @profile) %>
</p>
数据库表(以 User_id 作为外键)
USER TABLE PROFILE TABLE
------------------------ ------------------------
| Id | ---------- | Id |
------------------------ | ------------------------
| Email | ------------------ | User_id |
------------------------ ------------------------
| Password | | Name |
------------------------ ------------------------
| Password Confirmation | | Address |
------------------------ ------------------------
| Remember Token | | Age |
------------------------ ------------------------
| Created At | | Created At |
------------------------ -------------------------
| Updated At | | Updated At |
------------------------ -------------------------
【问题讨论】:
-
你记得运行
rake db:migrate吗?否则,请描述一下您的模型和数据库结构 -
@derekyau 是的,数据库已更新并包含必要的列。
-
你能发一些模型代码吗?
-
@derekyau,添加了一些代码,虽然我还没有让模型响应 json.. 谢谢。
标签: ruby-on-rails ruby