0

刚接触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)
4

1 回答 1

0

以下内容适用于遇到此问题的任何人:

在 routes.db 中,我将列表放在一个块中:

 resources :users do
      resource :listings
  end

对于 new/show/create 方法,我确保首先搜索用户(注意,因为我使用的是设计 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 %>
于 2013-07-05T03:14:35.200 回答