刚接触rails,不知道如何做到这一点。我已经使用设计实现了一个用户登录系统,我试图让用户创建多个“列表”。有点像 craigslist 类型的网站。我可以从 rails 控制台填充数据库,但我不知道如何将它放在网站上。
我有以下型号:
清单.rb
class Listing < ActiveRecord::Base
belongs_to :user
default_scope -> { order('created_at DESC') }
#add validations
validates :user_id, presence: true
end
user.rb(使用过的设计)
class User < ActiveRecord::Base
has_many :listings, dependent: :destroy
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
我正在尝试创建一个允许用户创建新列表的页面。我不完全确定如何去做。这是我目前拥有的:
Listings_controller.rb
class ListingsController < ApplicationController
def index
@users = User.all
end
def show
@listing = Listing.find(params[:id])
end
def new
@listing = Listing.new
end
def create
@listing = Listing.new(listing_params)
if @listing.save
flash[:success] = "Success"
redirect_to @listing
else
render 'new'
end
end
private
def listing_params
params.require(:listing).permit(:id, :user_id, :title, :general_info)
end
end
模型/视图/列表/new.html.erb
<h1> POST A NEW LISTING </h>
<%= form_for @listing do |f| %>
Title: <%= f.text_field :title %> <br />
General Info: <%= f.text_field :general_info %> <br />
<%= f.submit %>
<% end %>
我已经为此工作了很长一段时间,但没有成功填充数据库。目前,表单一旦提交,就会在 def create 中点击“else”并只呈现相同的页面。
这是我运行它时的日志输出:
Started POST "/listings" for 127.0.0.1 at 2013-07-04 17:37:53 -0600
Processing by ListingsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"mlyDb24OMQkniOCFQ1JTvzxjplHk7kMgzEBEFBH8hGw=", "listing"=>{"title"=>"title should go here", "general_info"=>"hope this works"}, "commit"=>"Create Listing"}
[1m[35m (0.1ms)[0m begin transaction
[1m[36m (0.1ms)[0m [1mrollback transaction[0m
[1m[35mUser Load (0.3ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered listings/new.html.erb within layouts/application (4.4ms)
Completed 200 OK in 17ms (Views: 10.4ms | ActiveRecord: 0.5ms)