【发布时间】:2013-04-17 19:48:14
【问题描述】:
我正在做一个授权申请,其中: -拥有管理员角色,可以管理一切。 -拥有访客角色,可以创建帖子并编辑他创建的帖子。
我面临来宾角色的问题。我做过以下协会: -posts belongs_to user(在帖子模型中,我在迁移中也有 user_id 属性,我已经引用了用户的帖子) -user has_many 帖子。
当我尝试创建新帖子时,user_id 为零。我不知道如何在 Post 对象中设置 user_id 属性。
类 ProductsController
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
视图:
添加产品
<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 %>
型号 类产品
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
请帮我解决这个问题....如果您需要任何进一步的信息,您可以询问...
【问题讨论】:
-
def create @product=Product.new(params[:product]) @product.user_id = current_user.id
-
thx....... itz 工作......
-
嘿...我还有一个问题。我想在我的应用程序中进行更改。我不希望每个人都注册为管理员。要注册为管理员,您需要有一个密钥。没有密钥 ucant 注册为管理员。你能帮我解决这个问题吗
-
你可以再问一个问题,这样即使我没有答案,别人也可以帮助你。
标签: ruby-on-rails