在我的rails应用中,我遇到了一个问题。作为一个抬头,我正在使用设计。
tracks_controller.rb
def new
@track = Track.new
end
def create
@track = current_user.tracks.build(params[:content])
if @track.save
flash[:success] = "Track created!"
redirect_to @user
else
render 'static_pages/home'
end
users_controller.rb
def show
@user = User.find(params[:id])
@tracks = @user.tracks
if signed_in?
@track = current_user.tracks.build
end
end
我以当前用户身份登录,当我尝试添加新曲目(通过当前用户)时,它不会保存..(而是重定向到root_url)
track.rb
class Track < ActiveRecord::Base
attr_accessible :content
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
validates :username, uniqueness: { case_sensitive: false }
has_many :tracks, dependent: :destroy
end
共享/ _track_form.html.erb
<%= form_for(@track) do |f| %>
<div class="track_field">
<%= f.text_area :content, placeholder: "Upload a youtube song URL...", :id => "message_area" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
/users/show.html.erb的相关部分
<div class="span8">
<% if signed_in? %>
<section>
<%= render 'shared/track_form' %>
</section>
<% end %>
我相信问题出在我的TracksController #create方法中,但是我无法理解。非常感谢任何帮助,谢谢!
答案 0 :(得分:1)
在您的控制器中create
操作更改
@track = current_user.tracks.build(params[:content])
到这个
@track = current_user.tracks.build(params[:track])
由于您使用了form_for(@track)
,因此params散列将包含填写到表单中的:content
字段。
现在,create
操作无法找到表单:content
,因为没有名为content
的表单。 content
是Track
模型的一个属性。