刚接触rails,不知道如何做到这一点。我已经使用design实现了一个用户登录系统,我正试图让用户创建多个"列表"。有点像craigslist类型的网站。我可以从rails控制台填充数据库,但我不知道如何将其放在网站上。
我有以下型号:
listing.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
models/views/listings/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)
以下内容使其适用于遇到此问题的任何人:
在routes.db中,我将列表放在一个块中:
resources :users do
resource :listings
end
对于新的/show/create方法,我确保首先搜索用户(注意,因为我使用的是design the current_user.id)
def show
@listing = Listing.find(current_user.id)
end
def new
@user = User.find(current_user.id)
@listing = @user.listings.build
end
def create
@user = User.find(current_user.id)
@listing = @user.listings.build(listing_params)
if @listing.save
flash[:success] = "Success"
redirect_to root_path
else
render :action => 'new'
end
end
最后,将new.html.erb中的form_for更改为:
<%= form_for [@user, @listing] do |f| %>
<%= f.label :title, 'Title' %> <br />
<%= f.text_field :title %>
...
<%= f.submit "submit" %>
<% end %>