ROR radio buttons for dummies?
-
13-11-2019 - |
質問
I have read the documentation on this, and still i have no idea how to do this.
I have a column in the table for :free that is a boolean
true = free
false = paid
nil = both
I'm trying to capture this same logic in my form and i'm doing an absolutely terrible job... so far everything comes up as free
index.html.erb:
<div class="field">
<label class="radio">
<%= radio_button_tag(:free, "free", :checked => true) %>
Free
</label>
<label class="radio">
<%= radio_button_tag(:free, "paid") %>
Paid
</label>
<label class="radio">
<%= radio_button_tag(:free, "both") %>
Both
</label>
</div>
resources_controller.rb (I know this isnt ideal because its checking the params every single time (even if they enter in wrong info) but i'm not sure how else to check if i can save it without saving it. Also... I dont even know if i did params right but i am not sure how to check it either. when i do p params[:resources]
it doesnt print it how id like it to. is there a good way to do this kind of thing in rails?
def create
@resource = Resource.new(params[:resource])
if params[:resource][:free] = "free"
@resource[:free] = true
elsif params[:resource][:free] = "both"
@resource[:free] = nil
else
@resource[:free] = false
end
if @resource.save
redirect_to root_url
else
render :action => :new
end
end
resources_helper.rb
def output_free
if @resource.free = true
"Free"
elsif @resource.free = false
"Paid"
else
"Both"
end
end
解決
That's fuzzy logic, true/false/null. Does exist in SQL, you could used that, but that's magic you don't want. Use an Enum and three states - way clearer.
And use ==
to compare :-)