开发者

How to create button in Rails app to let user modify ActiveRecord?

I want the user to click a link that will modify an ActiveRecord entry. The record is called feed.disabled and the link will toggle that record between true and false. I made a helper method to determine the text for the link:

def disable_button(feed)
  if feed.disabled?
    return 'Enable Feed'
  else
    return 'Disable Feed'
  end
end

So my question is really two-fold. Will that helper work to display the correct text in the view, and how do I get that link to modify the feed.disabled record to true or false depending on what the current state is?

Edit to add methods based on Dave's guide:

feeds_controller.rb:

def toggle_disabled_record
  @feed = Project.find(params[:project_id]).feeds.find(params[:id])
  @feed.toggle!(:disabled)
  re开发者_Python百科nder :nothing => true
end

projects->show.html.erb:

<%= link_to toggle_disable_button(feed), toggle_disabled_record_project_feed_path(feed) %>

routes.rb:

resources :projects do
  resources :feeds
end

resources :feeds do
  resources :xml_fields
  get toggle_disabled_record, :on => :member
end


Take a look at (my) this blog post; it's a link, not a button, but more or less directly addresses this.


The helper will work, but its name gives the idea that it would return the actual button element.

You could probably generate such a button using button_to with a helper looking something like this:

def toggle_disable_button(feed)
  button_text = feed.disabled? ? 'Enable feed' : 'Disable feed'

  button_to(button_text, toggle_feed_disabled_path(feed))
end

This is of course dependent on that you have a matching controller action and route. You might also be able to create a button like this:

button_tag(button_text, :name => 'feed[disabled]', :value => !feed.disabled?)

but this might not work in all browsers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜