in my rails app, I am running into an issue. As a heads up I am using devise.
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
I am logged in as a current user, and when I try to add a new track (through the current user) it is not saving.. (and instead redirects to 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
shared/_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" %>
relavent section for /users/show.html.erb
<div class="span8">
<% if signed_in? %>
<section>
<%= render 'shared/track_form' %>
</section>
<% end %>
I believe the issue is in my TracksController #create method, however I just can't figure it out. any help is greatly appreciated, thanks!
In your controller create
action change
@track = current_user.tracks.build(params[:content])
to this
@track = current_user.tracks.build(params[:track])
Since you used form_for(@track)
the params hash will contain the :content
field filled into the form.
The way you have it now the create
action cant find the form :content
because there isn't a form named content
. content
is an attribute of the Track
model.