对于您的上下文:这是我第一次尝试创建一个应用程序。我刚刚开始编码:-)。
我正在尝试一个简单的CRUD设置来工作。
现在我有两个问题,我不能把我的头弄清楚:
这是我的密码:
主计长:
class DecisionsController < ApplicationController
before_action :find_decision, only: [:show, :edit, :update]
def index
# gets all rows from decision table and puts it in @decision variable
@decisions = Decision.all
end
def show
# find only the decision entry that has the id defined in params[:id]
@decision = Decision.find(params["id"])
end
# shows the form for creating a entry
def new
@decision = Decision.new
end
# creates the entry
def create
@decision = Decision.new(decision_params)
if @decision.save
redirect_to @decision
else
render 'new'
end
end
# shows the form for editing a entry
def edit
@decision = Decision.find(params["id"])
end
# updates the entry
def update
end
def destroy
end
private
def find_decision
@decision = Decision.find(params["id"])
end
def decision_params
params.require(:decision).permit(:title, :forecast, :review_date)
end
end索引视图
<h1>Hello World ^^</h1>
<% @decisions.each do |descision| %>
<p><%= @decision.title %></p>
<% end %>routes.rb
Rails.application.routes.draw do
resources :decisions
root 'decisions#index'
end我整个上午都在研究这两个人,但我想不出来。如果你们能帮我看看,我会很有帮助的。
发布于 2015-10-20 12:37:27
我刚开始编码
欢迎!!
我的
entries没有出现在我的索引页面上。
我相信你是说decisions,对吧?
如果是这样的话,您必须记住,如果在Ruby中调用一个循环,那么在尝试调用它之前,需要一些条件逻辑来确定它是否实际填充了任何数据:
#app/views/decisions/index.html.erb
<% if @decisions.any? %>
<% @decisions.each do |decision| %>
<%= content_tag :p, decision.title %>
<% end %>
<% end %>这必须由适当的控制器代码匹配:
#app/controllers/decisions_controller.rb
class DecisionsController < ApplicationController
before_action :find_decision, only: [:show, :edit, :update, :destroy]
def index
@decisions = Decision.all
end
def show
end
def new
@decision = Decision.new
end
def create
@decision = Decision.new decision_params
@decision.save ? redirect_to(@decision) : render('new')
end
def edit
end
def update
end
def destroy
end
private
def find_decision
@decision = Decision.find params["id"]
end
def decision_params
params.require(:decision).permit(:title, :forecast, :review_date)
end
end这将使您能够在视图中调用@decisions和@decision,具体取决于您要访问的路由。
重要的一点是当你说..。
decisions/edit给出了以下错误:Couldn't find Decision with 'id'=edit'
..。这个问题是由处理Rails路由的方式引起的:

因为Rails是https://en.wikipedia.org/wiki/Object-oriented_programming,所以每一组路由都对应于对象集合或成员对象。这就是为什么像edit这样的路由需要传递一个"id“--它们被设计用来处理成员对象。
因此,当您访问任何“成员”路由(decisions/:id,decisions/:id/edit)时,您必须提供一个id,以便Rails能够从db中提取适当的记录:
#app/views/decisions/index.html.erb
<% if @decisions.any? %>
<% @decisions.each do |descision| %>
<%= link_to "Edit #{decision.title}", decision_edit_path(decision) %>
<% end %>
<% end %>我可以解释得更多--以上所述现在应该适用于你。
https://stackoverflow.com/questions/33233521
复制相似问题