0

在我的 Rails 应用程序中,我遇到了一个问题。作为提醒,我正在使用设计。

轨道控制器.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)

轨道.rb

class Track < ActiveRecord::Base
  attr_accessible :content
  belongs_to :user
end

用户.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 方法中,但我就是想不通。非常感谢任何帮助,谢谢!

4

1 回答 1

1

在您的控制器create操作更改中

@track = current_user.tracks.build(params[:content])

对此

@track = current_user.tracks.build(params[:track])

由于您使用form_for(@track)了 params 哈希将包含:content填写到表单中的字段。

您现在拥有它的方式,create操作无法找到表单:content,因为没有名为 的表单contentcontentTrack模型的一个属性。

于 2013-06-07T22:20:56.697 回答