Mat*_*tti 11 methods model-view-controller routes ruby-on-rails hyperlink
我正在尝试创建一个简单的链接,允许管理员批准我的网站上的用户
与这个家伙的尝试非常相似:在Rails 3中如何使用button_to来改变布尔值?
这是它应该如何工作:
这就是我要做的事情
在我的用户#index视图中
<% @users.each do |user| %>
<%= link_to 'Approve', :action => "index", :method => 'activate', :id => user.id, :class => 'btn btn-mini btn-danger' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
在我的userController中
def activate
@user = User.find(params[:user])
@user.activate_user
end
Run Code Online (Sandbox Code Playgroud)
在我的用户模型中
def activate_user
self.approved = 'true'
self.save
end
Run Code Online (Sandbox Code Playgroud)
和我的路线
devise_for :users, :controllers => { :registrations => "registrations" }
resources :users do
member do
get 'activate'
put 'activate'
end
end
match "users/:id/activate" => "users#activate"
Run Code Online (Sandbox Code Playgroud)
现在当我点击链接(批准用户)时,我被发送回用户索引页面(就像我应该的那样),但用户字段"approved"仍然设置为false:I
点击链接后我得到的网址:
http://localhost:3000/users?class=btn+btn-mini+btn-danger&id=2&method=activate
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
UPDATE
建议iv将URL添加到link_to帮助程序
<% @users.each do |user| %>
<%= link_to "Approve", :controller => "users", :id => user.id, :action => "activate", :method => :put, :approved => true %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
当我点击帮助链接时,我得到了
wrong number of arguments (1 for 2)
Run Code Online (Sandbox Code Playgroud)
在app/controllers/users_controller.rb中:7:在`activate'中
def activate
@user = User.find(params[:id])
@user.update_attribute(params[:user])
redirect_to "/users?approved=false"
end
Run Code Online (Sandbox Code Playgroud)
第7行,其中错误是@ user.update_attribute(params [:user])
还有什么我应该放在那里?
哦,这是我这种方法的路线
match "/users/:id/activate" => "users#activate"
Run Code Online (Sandbox Code Playgroud)
UPDATE V2 所以我已将更新行更改为:
@user.update_attributes(@user.approved, "true")
Run Code Online (Sandbox Code Playgroud)
它似乎做了我想要它做的一切,除了将值更改为true!
我也尝试使用1作为true(和update_attribute函数)和非字符串..这里的想法用完了lol
解决方案
嗯这很尴尬但是碰巧在我的用户模型中我得到了attr_accessor :approved 这导致模型从未进入数据库更新:approved列BUT而是更新了局部变量:approved所以下次当我查看列然后当然:approved价值没有改变
tldr?如果您的模型中的attr_accessor与您尝试更新的列名称相同=>将其删除
您可以更新以下代码
你查看
<% @users.each do |user| %>
<%= link_to 'Approve', active_user_path(user) %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
你控制器
def activate
@user = User.find(params[:id])
if @user.update_attribute(:approved, true)
redirect_to "something"
else
render "something"
end
end
Run Code Online (Sandbox Code Playgroud)
你的路线
match "users/:id/activate" => "users#activate", :as => "active_user"
Run Code Online (Sandbox Code Playgroud)
希望可以帮到你.
| 归档时间: |
|
| 查看次数: |
5139 次 |
| 最近记录: |