私は認可申請を行っています: -すべてを管理できる管理者の役割を持っています。-投稿を作成し、作成した投稿を編集できるゲストロールを持っています。
ゲストの役割で問題に直面しています。私は関連付けを行いました: -posts belongs_to user (post モデルでは user_id 属性があり、移行でも私はユーザーへの投稿を参照しています) -user has_many の投稿。
新しい投稿を作成しようとすると、user_id は nil です。Post オブジェクトに user_id 属性を設定する方法がわかりません。
class ProductsController < ApplicationController
before_filter :self_load, :only=>[:show,:edit,:update,:destroy]
before_filter :authenticate_user, :only=>[:edit,:update,:destroy]
def index
@products=Product.find(:all)
end
def new
@product=Product.new(:user_id=>current_user.id)
end
def create
@product=Product.new(params[:product])
if @product.save
redirect_to root_url, :notice=>'New Product has been added'
else
render :action=>'new'
end
end
def show
end
def edit
end
def update
if @product.update_attributes(params[:product])
redirect_to root_url, :notice=>'Product has been updated.'
else
render :action => 'edit'
end
end
def destroy
@product.destroy
redirect_to root_url
end
def self_load
@product = Product.find(params[:id])
end
def authenticate_user
if current_user
else
redirect_to root_url, :notice=>'You are not authorised to access'
end
end
end
見る:
製品を追加
<%= form_for(@product) do |f| %> <% if @product.errors.any? %> <ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<table>
<tr><td><%= f.label 'Title:' %></td>
<td><%= f.text_field :title %></td>
<tr><td><%= f.label 'Description:' %></td>
<td><%= f.text_area :description,:rows=>10 %></td></tr>
<tr><td><%= f.label 'Price:' %></td>
<td><%= f.text_field :price %></td></tr>
<tr><td><%= f.submit 'Save' %></td></tr>
</table>
<% end %>
<%= link_to 'Back', root_url %>
モデル クラス Product < ActiveRecord::Base
belongs_to :user
attr_accessible :title, :description, :price, :user_id
validates_presence_of :title, :description, :price
validates_uniqueness_of :title
validates_length_of :title, :in=>4..10
validates_length_of :description, :minimum=>10
validates_numericality_of :price
end
Plzはこれで私を助けてください....さらに情報が必要な場合は、尋ねることができます...