如何使用任何编辑gems par例如: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
为否果。
实际上代码可以在下面看到。
我实际上是用它来编辑用户的个人资料属性,但是类似的概念和错误......
User.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
Profile.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 |
------------------------ -------------------------
答案 0 :(得分:0)
您需要向update
profiles_controller
操作
类似的东西:
def update
@profile = Profile.find params[:id]
respond_to do |format|
if @profile.update_attributes(params[:profile])
format.json { respond_with_bip(@profile) }
end
end
end