[英]Simple learning app with Rails 4 - Course / Enrolment / User Not working
I am trying to build a simple learning app with rails 4. 我正在尝试使用Rails 4构建一个简单的学习应用程序。
here are my models: 这是我的模特:
class User < ActiveRecord::Base
has_many :enrollments
has_many :lectures, through: :enrollments
accepts_nested_attributes_for :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :user
belongs_to :lecture
end
class Lecture < ActiveRecord::Base
has_many :enrollments
has_many :users, through: :enrollments
end
And here are my controllers 这是我的控制器
class EnrollmentsController < ApplicationController
before_action :authenticate_user!
def create
@enrollments = current_user.enrollments.build(enrollment_params)
if @enrollments.save
flash[:success] = "You have successfully enrolled."
redirect_to profile_path(current_user)
else
flash[:danger] = "Please try again."
redirect_to root_path
end
end
private
def enrollment_params
params.require(:enrollment).permit(:user_id, :lecture_id)
end
end
Here are my views: 这是我的看法:
lectures/index.html.erb Lessons / index.html.erb
<% @lectures.each do |lecture| %>
<%= image_tag lecture.picture.url(:medium) %>
<p><%= truncate(lecture.description, length: 80) %> </p>
<%= link_to "Enroll Now", {:action=>"create", :controller=>"enrollments"}, :method => :post %>
<% end %>
The problem is that when you click on Enroll Now I have the following error: 问题是,当您单击立即注册时,出现以下错误:
ActionController::ParameterMissing in EnrollmentsController#create param is missing or the value is empty: enrollment EnrollmentsController#create参数中的ActionController :: ParameterMissing丢失或值为空:enrollment
def enrollment_params
params.require(:enrollment).permit(:user_id, :lecture_id)
end
How can i make it work? 我该如何运作? Need help please 请帮忙
In your lectures/index.html.erb
file, you are not passing any data to the controller's action method. 在您的lectures/index.html.erb
文件中,您没有将任何数据传递到控制器的action方法。
<%= link_to "Enroll Now", {:action=>"create", :controller=>"enrollments"}, :method => :post %>
Might be better served with something a la 最好搭配点菜
<%= link_to "Enroll Now", {:action=>"create", :controller=>"enrollments", :user_id => current_user.id**, :lecture_id => lecture.id}, :method => :post %>
# ** not sure how you snag the current user's id in your app but you'd need it.
Also, take a look at Routing in Rails . 另外,看看Rails中的Routing 。 There are some super handy helper methods you can use that will allow you to do something like this (this was done quickly and may not be totally accurate but is offered to show you how you can use a route's path helper to clean up the code and make it even more readable): 您可以使用一些超级方便的辅助方法,这些方法可以使您执行以下操作(此操作很快完成,可能并不完全准确,但是可以向您展示如何使用路线的路径辅助方法来清理代码并使它更具可读性):
<%= link_to 'Enroll Now', enrollments_path({enrollment: { user_id: current_user.id, lecture_id: lecture.id }}), :method => :post %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.