在我的应用程序中,当前用户通过 index.html.erb
现在我想将该值绑定(bind)到一个实例变量并在 View 中显示该实例变量。
我是 ruby on rails 的新手,所以我不确定如何管理它。
我尝试了各种类型的代码来访问数据,但都没有成功。 谁能帮我解决这个问题?
例如:
@general_goal = Goal.find(params[:id])
general_goal = @general_goal.user.general_goal
给出了错误:Couldn't find Goal with 'id'=
和
@general_goal = Goal.find(params[:general_goal])
还给出错误:Couldn't find Goal with 'id'=
这是goals_controller.rb
class GoalsController < ApplicationController
before_action :set_goal, only: [:edit, :update, :show, :destroy]
#before_action :goal_owner, only: [ :edit, :update, :destroy]
def new
@goal = current_user.goals.build
end
def index
@Newgeneralgoal = Goal.new
@goals = current_user.goals.order(created_at: :desc).limit(5)
end
def create
@goal = Goal.new(goal_params)
@goal.user_id = current_user.id
if (@goal.save)
redirect_to transaction_path(current_user), :notice => "Goal has been saved successfully."
else
f.html { redirect_to "", notice: "Error: Goal Not created!!"}
end
end
def update
if @goal.update(goal_params)
flash[:success] = "Goal was successfully updated"
redirect_to goals_path(@goal)
else
render 'edit'
end
def destroy
@goal.destroy
flash[:danger] = "Goal was successfully destroyed"
redirect_to goal_path(current_user)
end
private
def set_goal
@goal = Goal.find(params[:id])
end
def goal_params
params.require(:goal).permit(:user_id, :general_goal, :date)
end
end
我可以通过以下方式访问 View 中的目标:
<% @goals.each do |goal| %>
<tr>
<td><%= goal.date.try(:strftime,"%Y/%m/%d")%></td>
<td><%= goal.general_goal %></td>
</tr>
<% end %>
所以我基本上是在问,如果用户将一般目标设置为“5”,我如何从数据库中获取“5”并将其分配给变量?
这是目标的schema.rb
create_table "goals", force: :cascade do |t|
t.datetime "date"
t.decimal "general_goal"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
这是 goal.rb 模型
class Goal < ActiveRecord::Base
belongs_to :user
end
这里是user.rb模型
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 :goals
end
最佳答案
如果我没理解错的话,你想为 current_user
显示 :general_goal
的值?
这可能对您有用,只需将这段代码放在 Controller 的 index
中。我还没有测试过它,但它可能会起作用。
current_general_goal = @current_user.goals.sum(:general_goal)
@general_goal = current_general_goal.nil? ? 0 : current_general_goal
它检查 :general_goal 是否为 nil,如果是则显示 0,否则显示一般目标值。
更新
如果您想要来自当前用户的最后一个 general_goal
的值。您可以将此代码添加到索引 View 中。
current_general_goal = @current_user.goals.last.general_goal
@general_goal = (current_general_goal.nil? ? 0 : current_general_goal)
请告诉我这是否适合你
关于ruby-on-rails - 从 Ruby on Rails 应用程序中的模型访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718839/