控制器:
def show
@user = User.find(params[:id])
@goal = @user.goals.find(params[:id])
render :template => 'goals/show'
end
查看(show.html.erb):
<%= @goal.text %>
我添加了您好,世界文本,只是为了检查链接是否将显示为show.html.erb。它是。问题是<%= @ goal.text%>变成空白。
已经处理了好几天...非常感谢您的帮助。
在控制器中创建和新建:
def new
@user = current_user
@goal = @user.goals.new
#for index
@goal = @user.goals
end
def create
@user = User.find(params[:id])
@goal = @user.goals.create(goal_params)
if @goal.save
redirect_to new_user_goal_path, notice: "Success!~"
else
redirect_to new_user_goal_path, alert: "Failure!"
end
end
private
def goal_params
params.require(:goal).permit(:text)
end
我在new.html.erb中列出了目标:
<table>
<tr>
<th>Text</th>
<th></th>
</tr>
<% @user.goals.each do |goal| %>
<tr>
<td><%= link_to goal.text, goal_path(@user,goal)%></td>
</tr>
<% end %>
</table>
<h2>Add a goal:</h2>
<%= form_for([@user, @user.goals.build]) do |form| %>
<p>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
一点-我一直专注于解决此问题,因此create现在似乎不起作用。我一定在绝望中改变了一些东西。如果可以的话,也请让我知道您在其中看到的错误,我将非常感谢。
也可以路由:
devise_for :users
resource :user do
resources :goals, shallow: true
end
devise_scope :user do
authenticated :user do
root 'home#index', as: :authenticated_root
end
unauthenticated do
root 'devise/sessions#new', as: :unauthenticated_root
end
end
更新: 我的架构,以防万一:
ActiveRecord::Schema.define(version: 2019_07_02_174954) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "goals", force: :cascade do |t|
t.text "text"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "user_id"
t.index ["user_id"], name: "index_goals_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "goals", "users"
end
答案 0 :(得分:0)
我认为这可能对您有用:
goals_controller.rb:
def new
@user = current_user
@goal = Goal.new
end
def create
@goal = current_user.goals.new(goal_params)
if @goal.save
redirect_to new_user_goal_path, notice: "Success!~"
else
redirect_to new_user_goal_path, alert: "Failure!"
end
end
def show
@goal = Goal.find(params[:id])
end
private
def goal_params
params.require(:goal).permit(:text)
end
show.html.erb:
<%= @goal.text %>
new.html.erb:
<table>
<tr>
<th>Text</th>
<th></th>
</tr>
<% @user.goals.each do |goal| %>
<tr>
<td><%= link_to goal.text, goal_path(goal.id)%></td>
</tr>
<% end %>
</table>
<h2>Add a goal:</h2>
<%= form_for([@user, @goal]) do |form| %>
<p>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>