mar*_*ion 5 model-view-controller ruby-on-rails ruby-on-rails-3
也许这甚至可以成为社区Wiki,但我希望详细描述控制器的工作原理 - 或者更确切地说,我如何能够让它做我想做的事情.
我理解MVC的一般结构以及模型如何存储db结构,并且控制器与db交互并将信息传递给视图.
但是,我(在基础层面上)对如何使用我的控制器完成简单任务感到困惑.我知道如果我想为模型/对象创建一个新记录,我只是object = Object.new(:name => "Object Name")在Rails控制台中.
但是我怎么能在控制器的CRUD元素中做到这一点,为什么呢?
请使用一个简单的例子 - 例如向用户显示他们的银行账户余额(我知道有很多复杂性,但为了这个解释而忽略它们).该模型的外观如何(仅包括:名称,地址,交易类型(存款/取款),余额).
视图会是什么样子?控制器会是什么样子?您做出的任何选择(如使用表格)请解释.为什么要使用表单,而不是下拉菜单和(通俗地说)表单或下拉菜单如何与控制器交互?如何将数据捕获到数据库中,为什么我这样做呢?
我知道这听起来好像很多要问,但我已经做了RailsTutorial.org,看了很多Railscasts,读了Rails指南,并阅读其他许多教程和仍然在我的方式了解一些基本的Rails差距作品,以及为什么.
提前致谢.
我不知道自己可以提供多少帮助,但我理解你自己的痛苦.ghoppe推荐的文章"Skinny Controller,Fat Model"很好地解释了Ms Vs&Cs的功能.看来这并没有完全回答你的问题,我将尝试解释每个结构的机制.
class Account < ActiveRecord::Base
belongs_to :user
validates_presence_of :address
def name # Account does not have a name field, but User does so I will make a name method for Account and feed it name of the user it belongs to.
user = self.user # Account gets the user method with the <belongs_to :user> association
# note: Rails expects Accounts to have a user_id field so it can perform the "magic" to associate Accounts with Users
if user.name
return user.name
else
return nil
end
end
end
Run Code Online (Sandbox Code Playgroud)
该模型描述了您的对象.就像任何OOP语言中的对象一样,您希望将所有对象逻辑放在此处.这包括用于关联的rails帮助程序(has_one,belongs_to,...)和验证,以及您希望对象能够在整个模型视图和控制器中使用的任何其他方法或库.
class AccountsController < ApplicationController
before_filter :name, :only => :edit, :destroy # @account.name will be executed before the edit or destroy method(action) can be invoked on @account. If the user who has the account has a name the action will execute.
def index # This is a RESTful action and is mapped by Rails by default to an HTTP GET request. Rails expects an index.html.erb or index.haml.erb or index.something in the Accounts view to map this action to.
@accounts = Account.all # @accounts is an instance variable and will be accessible in the view this action is mapped to.
end
def show
@account = Account.find(params[:id]) # params[:id] is passed to the controller from the view. The params hash is the primary tool form moving data from a form or URL into a controller. Anytime you click on the link_to the show or edit action of an object Rails will put that objects id in the params hash and call the appropriate action in that objects controller. If you click the show link on an account it will call this action. Now the instance variable in the view show.html.erb will hold a single account instead of an array
end
def new
@account = Account.new # This initializes a new account with all the fields set to blank unless you specified a default in your migration. This account has not been save to the db yet. It is ready for a user to fill in.
respond_to do |format| # Rails can automatically respond differently to different client request. If a client i.e browser wants HTML rails responds with HTML. If a client e.g. an API want XML Rails responds with XML.
format.html # new.html.erb #
format.xml { render :xml => @account }
end
end
def edit
@account = Account.find(params[:id]) # Same as show, but mapped to a different view
end
def create # Finally we have a POST. All the prior actions were GETs, but now we are saving some data to the db.
@account = Account.new(params[:account]) # The :account key is special. It is a hash of hashes. It is populated by the form fields in new.html.erb. To access a specific field such as address we say <params[:account][:address]> and whatever the user entered in the address field in the View is at out fingers in the Controller.
respond_to do |format|
if @account.save # If the validations pass and the account gets saved redirect to the show page of the new record, otherwise refresh/render the new page (hopefully showing what error caused the record to fail to save).
format.html { redirect_to(@account, :notice => 'Account was successfully created.') }
format.xml { render :xml => @account, :status => :created, :location => @account }
else
format.html { render :action => "new" }
format.xml { render :xml => @account.errors, :status => :unprocessable_entity }
end
end
end
def update # This is another of the seven RESTful Rails actions and results in a PUT request because you are updating an existing record
@account = Account.find(params[:id])
respond_to do |format|
if @account.update_attributes(params[:account])
format.js # Rails can also respond with JavaScript. Look up UJS. Rails 3 has made large improvements here.
format.html { redirect_to(@account, :notice => 'Account was successfully updated.') }
format.xml { head :ok }
else
format.js
format.html { render :action => "edit" }
format.xml { render :xml => @account.errors, :status => :unprocessable_entity }
end
end
end
def destroy # This results in a DELETE
@account = Account.find(params[:id])
@account.destroy # destroy is a more thourough delete and will check the options of this records associations and destroy the associated objects as well if they are dependant on this object. The option <:dependant => :destroy> is not set for this object's only association: User. The user this account belongs to will therefore survive the destruction of this account.
respond_to do |format|
format.html { redirect_to(accounts_url) }
format.xml { head :ok }
end
end
end
Run Code Online (Sandbox Code Playgroud)
希望你能从这里得出你自己的逻辑.该视图旨在将从实例变量传递的信息从控制器呈现到客户端:浏览器,api,智能手机.以及通过params散列将信息从客户端传递到控制器.即使具有erb的视图具有执行任何ruby代码的能力,也不应在视图中执行复杂的逻辑.
如果示例视图也有帮助,我很乐意帮忙.
| 归档时间: |
|
| 查看次数: |
2399 次 |
| 最近记录: |